How to construct a std::string from a std::vector<char>?

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-17 06:33:52

问题


Short of (the obvious) building a C style string first then using that to create a std::string, is there a quicker/alternative/"better" way to initialize a string from a vector of chars?


回答1:


Well, the best way is to use the following constructor:

template<class InputIterator> string (InputIterator begin, InputIterator end);

which would lead to something like:

std::vector<char> v;
std::string str(v.begin(), v.end());



回答2:


I think you can just do

std::string s( MyVector.begin(), MyVector.end() );

where MyVector is your std::vector.




回答3:


With C++11, you can do std::string(v.data()) or, if your vector does not contain a '\0' at the end, std::string(v.data(), v.size()).




回答4:


std::string s(v.begin(), v.end());

Where v is pretty much anything iterable. (Specifically begin() and end() must return InputIterators.)




回答5:


Just for completeness, another way is std::string(&v[0]) (although you need to ensure your string is null-terminated and std::string(v.data()) is generally to be preferred.

The difference is that you can use the former technique to pass the vector to functions that want to modify the buffer, which you cannot do with .data().




回答6:


I like Stefan’s answer (Sep 11 ’13) but would like to make it a bit stronger:

If the vector ends with a null terminator, you should not use (v.begin(), v.end()): you should use v.data() (or &v[0] for those prior to C++17).

If v does not have a null terminator, you should use (v.begin(), v.end()).

If you use begin() and end() and the vector does have a terminating zero, you’ll end up with a string "abc\0" for example, that is of length 4, but should really be only "abc".



来源:https://stackoverflow.com/questions/5115166/how-to-construct-a-stdstring-from-a-stdvectorchar

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!