Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vector <unsigned char> vs string for binary data

Which is a better c++ container for holding and accessing binary data?

std::vector<unsigned char> 

or

std::string 

Is one more efficient than the other?
Is one a more 'correct' usage?

like image 467
kalaxy Avatar asked Oct 12 '09 18:10

kalaxy


2 Answers

You should prefer std::vector over std::string. In common cases both solutions can be almost equivalent, but std::strings are designed specifically for strings and string manipulation and that is not your intended use.

like image 93
David Rodríguez - dribeas Avatar answered Oct 09 '22 02:10

David Rodríguez - dribeas


Both are correct and equally efficient. Using one of those instead of a plain array is only to ease memory management and passing them as argument.

I use vector because the intention is more clear than with string.

Edit: C++03 standard does not guarantee std::basic_string memory contiguity. However from a practical viewpoint, there are no commercial non-contiguous implementations. C++0x is set to standardize that fact.

like image 31
fnieto - Fernando Nieto Avatar answered Oct 09 '22 04:10

fnieto - Fernando Nieto