C++ 如何从 std::vector<char> 构造 std::string?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5115166/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 17:25:37  来源:igfitidea点击:

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

c++

提问by oompahloompah

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?

除了(显而易见的)首先构建 C 样式字符串然后使用它来创建 std::string 之外,是否有更快/替代/“更好”的方法来从字符向量初始化字符串?

回答by Greg

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());

回答by LiMuBei

I think you can just do

我想你可以做

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

where MyVector is your std::vector.

其中 MyVector 是您的 std::vector。

回答by ?tefan

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()).

使用 C++11,您可以执行std::string(v.data())或者,如果您的向量'\0'末尾不包含 a ,则std::string(v.data(), v.size()).

回答by Martin Stone

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

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

其中 v 几乎是任何可迭代的东西。(特别是 begin() 和 end() 必须返回 InputIterators。)

回答by Riot

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.

只是为了完整性,另一种方法是std::string(&v[0])(尽管您需要确保您的字符串以空字符结尾并且std::string(v.data())通常是首选的。

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().

不同之处在于您可以使用前一种技术将向量传递给想要修改缓冲区的函数,而使用 .data() 则无法做到这一点。

回答by Henri Raath

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

我喜欢 Stefan 的回答(2013 年 9 月 11 日),但想让它更强大一点:

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).

如果向量以空终止符结尾,则不应使用 (v.begin(), v.end()):您应该使用 v.data() (或 &v[0] 用于 C++17 之前的那些) .

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

如果 v 没有空终止符,则应使用 (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".

如果您使用 begin() 和 end() 并且向量确实有一个终止零,那么您最终会得到一个字符串“abc\0”,例如,长度为 4,但实际上应该只是“abc”。

回答by TechCat

vector<char> vec;
//fill the vector;
std::string s(vec.begin(), vec.end());