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
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:
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::copyis as optimised as it gets, so perhaps (measure!) the following is faster: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.