How to efficiently copy std :: vector <char> to std :: string
This question is the flip side of this How to efficiently copy std :: string to a vector
I usually copy the vector this way (a zero-terminated string)
std::string s((char*)&v[0]);
or (if the string is already declared), for example,
s = (char*)&v[0];
He is doing his job, but maybe there are better ways.
EDIT
C-style casts are ugly, I was told about it
s = reinterpret_cast<char*>(&vo[0]);
+5
3 answers
Just use the iterator constructor:
std::string s(v.begin(), v.end());
(): char -pointer-plus-size:
std::string s(v.data(), v.size()); // or &v[0]
, char* -constructor:
std::string s(v.data()); // or &v[0]
s.assign(v.begin(), v.end());
s.assign(v.data(), v.size()); // pointer plus size
s.assign(v.data()); // null-terminated
+12
s.resize( v.size() );
std::copy( v.begin(), v.end(), s.begin() );
You can somehow ... because once these damned compilers understand the power of standardization, this method will be faster than any other ...
And a more serious note:
std::string( (char*)v.data(), v.size() );
s.assign( (char*)v.data(), v.size() );
... could be safer without loss of effectiveness.
+1