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?
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?
You should prefer
std::vector
overstd::string
. In common cases both solutions can be almost equivalent, butstd::string
s are designed specifically for strings and string manipulation and that is not your intended use.As far as readability is concerned, I prefer std::vector. std::vector should be the default container in this case: the intent is clearer and as was already said by other answers, on most implementations, it is also more efficient.
On one occasion I did prefer std::string over std::vector though. Let's look at the signatures of their move constructors in C++11:
vector (vector&& x);
string (string&& str) noexcept;
On that occasion I really needed a noexcept move constructor. std::string provides it and std::vector does not.
This is the wrong question.
This is the correct question.
It depends. How is the data being used? If you are going to use the data in a string like fashon then you should opt for std::string as using a std::vector may confuse subsequent maintainers. If on the other hand most of the data manipulation looks like plain maths or vector like then a std::vector is more appropriate.