Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to efficiently copy a std::string into a vector

I have a string

std::string s = "Stack Overflow";

That I need to copy into a vector. This is how I am doing it

std::vector<char> v;
v.reserve(s.length()+1);
for(std::string::const_iterator it = s.begin(); it != s.end(); ++it)
{
    v.push_back( *it );
}
v.push_back( '\0' );

But I hear range operation are more efficient. So I am thinking something like this

std::vector<char> v( s.begin(), s.end());
v.push_back('\0');

But is this better in this case? What about the potential re-allocation when inserting '\0'?
Another approach I am thinking is this

std::vector<char> v(s.length()+1);
std::strcpy(&v[0],s.c_str());

Perhaps fast but potentially unsafe?
EDIT
Has to be a null terminated string that can be used ( read/write ) inside a C function

like image 348
molita Avatar asked May 13 '26 22:05

molita


1 Answers

If you really need a vector (e.g. because your C function modifies the string content), then the following should give you what you want, in one line:

std::vector<char> v(s.c_str(), s.c_str() + s.length() + 1);

Since c_str() returns a null-terminated string, you can just copy it whole into the vector.

However, I’m not actually sure how optimised this constructor is. I do know that std::copy is as optimised as it gets, so perhaps (measure!) the following is faster:

std::vector<char> v(s.length() + 1);
std::copy(s.c_str(), s.c_str() + s.length() + 1, v.begin());

If the C function doesn’t modify the string, just pass c_str() directly, and cast away const-ness. This is safe, as long as the C function only reads from the string.

like image 104
Konrad Rudolph Avatar answered May 15 '26 11:05

Konrad Rudolph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!