[c++] How to construct a std::string from a std::vector<char>?

Short of (the obvious) building a C style string first then using that to create a std::string, is there a quicker/alternative/"better" way to initialize a string from a vector of chars?

This question is related to c++

The answer is


I like Stefan’s answer (Sep 11 ’13) but would like to make it a bit stronger:

If the vector ends with a null terminator, you should not use (v.begin(), v.end()): you should use v.data() (or &v[0] for those prior to C++17).

If v does not have a null terminator, you should use (v.begin(), v.end()).

If you use begin() and end() and the vector does have a terminating zero, you’ll end up with a string "abc\0" for example, that is of length 4, but should really be only "abc".


Just for completeness, another way is std::string(&v[0]) (although you need to ensure your string is null-terminated and std::string(v.data()) is generally to be preferred.

The difference is that you can use the former technique to pass the vector to functions that want to modify the buffer, which you cannot do with .data().


I think you can just do

std::string s( MyVector.begin(), MyVector.end() );

where MyVector is your std::vector.


std::string s(v.begin(), v.end());

Where v is pretty much anything iterable. (Specifically begin() and end() must return InputIterators.)


vector<char> vec;
//fill the vector;
std::string s(vec.begin(), vec.end());

With C++11, you can do std::string(v.data()) or, if your vector does not contain a '\0' at the end, std::string(v.data(), v.size()).