'Converting std::string to std::vector<char>

I am using a library which accepts data as a vector of chars. I need to pass a string to the library.

I think about using std::vector constructor which accepts iterators to carry out the conversion - but wondered if there is a better way of doing it?

/*Note: json_str is of type std::string*/
const std::vector<char> charvect(json_str.begin(), json_str.end()); 
c++


Solution 1:[1]

Your method of populating the vector is fine -- in fact, it's probably best in most cases.

Just so that you know however, it's not the only way. You could also simply copy the contents of the string in to the vector<char>. This is going to be most useful when you either have a vector already instantiated, or if you want to append more data to the end -- or at any point, really.

Example, where s is a std::string and v is a std::vector<char>:

std::copy( s.begin(), s.end(), std::back_inserter(v));

As with the constructor case, if you need a null-terminator then you'll need to push that back yourself:

v.push_back('\0');

Solution 2:[2]

You can do it in this way.

  std::string s = "Hello World!";
    std::vector<char> v(s.begin(), s.end());
    for (const char &c: v)
        std::cout << c;

Solution 3:[3]

An alternative that might be worth considering if you need the terminating null is:

std::vector<char> charvect(json_str.c_str(), json_str.c_str() + json_str.size() + 1); 

and if charvect already exists you can do:

charvect.assign(json_str.c_str(), json_str.c_str() + json_str.size() + 1);

This might be quicker than doing a push_back('\0') particularly if the push_back triggers a memory reallocation.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 John Dibling
Solution 2 Mark
Solution 3 Bill Sellers