Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 this

s = reinterpret_cast<char*>(&vo[0]);
like image 926
karimjee Avatar asked Sep 12 '11 01:09

karimjee


2 Answers

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
like image 168
Kerrek SB Avatar answered Sep 18 '22 10:09

Kerrek SB


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() );
like image 31
Gnawme Avatar answered Sep 18 '22 10:09

Gnawme