How to efficiently copy a std::vector<char> to a std::string
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 thiss = 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() );
s.resize( v.size() );
std::copy( v.begin(), v.end(), s.begin() );
You may as why... because once those damn compiler creators understand the power of standarization, this method will be way faster than any other...
And on a more serious note:
std::string( (char*)v.data(), v.size() );
s.assign( (char*)v.data(), v.size() );
... might be safer, without loosing efficiency.
精彩评论