What is the correct (and efficient) way of attaching the contents of C buffer (char *) to the end of std::vector?
Thanks.
What is the correct (and efficient) way of attaching the contents of C buffer (char *) to the end of std::vector?
Thanks.
When you have a vector<char>
available, you're probably best calling the vector<char>::insert
method:
std::vector<char> vec;
const char* values="values";
const char* end = values + strlen( values );
vec.insert( vec.end(), values, end );
Delegating it to the vector is to be preferred to using a back_inserter
because the vector can then decide upon it's final size. The back_inserter
will only push_back
, possibly causing more reallocations.
char c[]="mama";
string s="tata";
s.insert(s.end(),c,c+4);
4 being the size of the c string
I think the proper way would be to
vec.insert(vec.end(),buf,buf+length);
or
std::copy(buf,buf+length,std::back_inserter(vec));
Edit: I reordered two examples, so it's not that commenters are wrong, it's just me ;-)
I haven't compiled it, but it should be something like:
const char string1[] = "a string";
std::vector<char> vData;
vData.insert(vData.end(), string1, string1+strlen(string1));