问题
It's known to everyone of us that we should prefer string
class in C++
for all string applications due to the many special functions they perform & their ability to grow & reduce dynamically. What string
is for characters
, vector
is for other data types & classes because it shows great performance.
However is there any situation where we would need to prefer vector<char>
(which I see seldom) over string
?
回答1:
I'd use vector<char>
only if I explicitly intent to store an array of char values, which is not a string. E.g. if for some reason I'd collect all the characters used somewhere in a specific text, the result might be a vector<char>
.
To be clear: it is all about expressing the intent.
回答2:
To put it briefly: if you're storing text, then string
, otherwise vector<char>
.
来源:https://stackoverflow.com/questions/33132363/c-strings-vs-vectorchar