tags:

views:

710

answers:

4

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

Thanks.

+10  A: 

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.

xtofl
A: 
char c[]="mama";
string s="tata";
s.insert(s.end(),c,c+4);

4 being the size of the c string

csiz
`std::vector` is not exactly `std::string` ;-)
Michael Krelin - hacker
+3  A: 

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

Michael Krelin - hacker
While the first is correct, too, the second it better, because the vector can deduce that the iterators are random-access iterators and use them to reserve beforehand, saving possible re-allocations.
sbi
True. I wouldn't expect that much from it, though. Anyway, there's more than one road to Rome ;-)
Michael Krelin - hacker
I'd actually expect the second to be better, because many modern implementations now optimize simple cases. This is simple in three ways: `vector<>` is a simple template, `char*` is a simple iterator, and `char` is a simple POD.
MSalters
I'll reorder them on popular demand, but the main point I'm trying to make is that it's good to have more than one way. Thanks MSalters and sbi for your comments.
Michael Krelin - hacker
+1  A: 

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