How to construct a std::string from a std::vector<char>?

C++

C++ Problem Overview


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?

C++ Solutions


Solution 1 - C++

Well, the best way is to use the following constructor:

template<class InputIterator> string (InputIterator begin, InputIterator end);

which would lead to something like:

std::vector<char> v;
std::string str(v.begin(), v.end());

Solution 2 - C++

I think you can just do

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

where MyVector is your std::vector.

Solution 3 - C++

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()).

Solution 4 - C++

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

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

Solution 5 - C++

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".

Solution 6 - C++

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().

Solution 7 - C++

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionoompahloompahView Question on Stackoverflow
Solution 1 - C++GregView Answer on Stackoverflow
Solution 2 - C++LiMuBeiView Answer on Stackoverflow
Solution 3 - C++ȘtefanView Answer on Stackoverflow
Solution 4 - C++Martin StoneView Answer on Stackoverflow
Solution 5 - C++Henri RaathView Answer on Stackoverflow
Solution 6 - C++RiotView Answer on Stackoverflow
Solution 7 - C++TechCatView Answer on Stackoverflow