Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attaching char buffer to vector<char> in STL

Tags:

What is the correct (and efficient) way of attaching the contents of C buffer (char *) to the end of std::vector<char>?

like image 655
jackhab Avatar asked Sep 09 '09 13:09

jackhab


2 Answers

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.

like image 172
xtofl Avatar answered Oct 08 '22 22:10

xtofl


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 ;-)

like image 32
Michael Krelin - hacker Avatar answered Oct 08 '22 22:10

Michael Krelin - hacker