vector vs string for binary data

2020-01-30 08:28发布

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?

9条回答
叛逆
2楼-- · 2020-01-30 09:14

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.

查看更多
一纸荒年 Trace。
3楼-- · 2020-01-30 09:19

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.

查看更多
Viruses.
4楼-- · 2020-01-30 09:23

Is one more efficient than the other?

This is the wrong question.

Is one a more 'correct' usage?

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.

查看更多
登录 后发表回答