This question is a flip side of this How to efficiently copy a std::string into a vector
I typically copy the vector this way ( null terminated string )
std::string s((char*)&v[0]);
or ( if the string has already been declared ) like this
s = (char*)&v[0];
It gets the job done but perhaps there are better ways.
EDIT
C-style casts are ugly, I am told so what about this
s = reinterpret_cast<char*>(&vo[0]);
Just use the iterator constructor:
std::string s(v.begin(), v.end());
(Edit): Or use the char-pointer-plus-size constructor:
std::string s(v.data(), v.size()); // or &v[0]
If your string is null-terminated and you want to omit the terminator, then use a char*
-constructor:
std::string s(v.data()); // or &v[0]
Update: As @Dave says, you can use the same syntax for assigning to an existing string:
s.assign(v.begin(), v.end());
s.assign(v.data(), v.size()); // pointer plus size
s.assign(v.data()); // null-terminated
std::string s( &v[ 0 ] );
generates less than half the number of lines of assembly code in Visual C++ 2005 as
std::string s( v.begin(), v.end() );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With