Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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());  
like image 868
Homunculus Reticulli Avatar asked Nov 23 '11 19:11

Homunculus Reticulli


People also ask

What is the difference between std::string and std :: vector?

std::string offers a very different and much expanded interface compared to std::vector<> . While the latter is just a boring old sequence of elements, the former is actually designed to represent a string and therefore offers an assortment of string-related convenience functions.

What is a vector in CPP?

Vectors in C++ are sequence containers representing arrays that can change in size. They use contiguous storage locations for their elements, which means that their elements can also be accessed using offsets on regular pointers to its elements, and just as efficiently as in arrays.


2 Answers

Nope, that's the way to do it, directly initializing the vector with the data from the string.

As @ildjarn points out in his comment, if for whatever reason your data buffer needs to be null-terminated, you need to explicitly add it with charvect.push_back('\0').

Also note, if you want to reuse the buffer, use the assign member function which takes iterators.

like image 187
Xeo Avatar answered Oct 05 '22 01:10

Xeo


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'); 
like image 39
John Dibling Avatar answered Oct 05 '22 01:10

John Dibling