What is the correct (and efficient) way of attaching the contents of C buffer (char *
) to the end of std::vector<char>
?
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 its final size. The back_inserter
will only push_back
, possibly causing more reallocations.
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 ;-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With