C++ 将 std::string 转换为 std::vector<char>

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8247793/
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 18:15:32  来源:igfitidea点击:

Converting std::string to std::vector<char>

c++

提问by Homunculus Reticulli

I am using a library which accepts data as a vectorof chars. I need to pass a stringto the library.

我使用的接收数据作为图书馆vectorchar秒。我需要将 a 传递string给图书馆。

I think about using std::vectorconstructor which accepts iterators to carry out the conversion - but wondered if there is a better way of doing it?

我考虑使用std::vector接受迭代器的构造函数来执行转换 - 但想知道是否有更好的方法来做到这一点?

/*Note: json_str is of type std::string*/
const std::vector<char> charvect(json_str.begin(), json_str.end()); 

采纳答案by Xeo

Nope, that's the way to do it, directly initializing the vector with the data from the string.

不,这就是这样做的方法,直接用字符串中的数据初始化向量。

As @ildjarn points out in his comment, if for whatever reason your data buffer needs to be null-terminated, you need to explicitly add it with charvect.push_back('\0').

正如@ildjarn 在他的评论中指出的那样,如果由于某种原因您的数据缓冲区需要以空值结尾,您需要显式地添加charvect.push_back('\0').

Also note, if you want to reuse the buffer, use the assignmember function which takes iterators.

另请注意,如果您想重用缓冲区,请使用assign带有迭代器的成员函数。

回答by John Dibling

Your method of populating the vectoris fine -- in fact, it's probably best in most cases.

您填充 的vector方法很好 - 事实上,在大多数情况下它可能是最好的。

Just so that you know however, it's not the only way. You could also simply copy the contents of the stringin to the vector<char>. This is going to be most useful when you either have a vectoralready instantiated, or if you want to append more data to the end -- or at any point, really.

只是为了让您知道,这不是唯一的方法。您也可以简单地将stringin的内容复制到vector<char>. 当您vector已经实例化了一个,或者您想在末尾附加更多数据时,这将是最有用的 - 或者在任何时候,真的。

Example, where sis a std::stringand vis a std::vector<char>:

示例,其中s是 astd::stringv是 a std::vector<char>

std::copy( s.begin(), s.end(), std::back_inserter(v));

As with the constructor case, if you need a null-terminator then you'll need to push that back yourself:

与构造函数的情况一样,如果您需要一个空终止符,那么您需要自己将其推回:

v.push_back('##代码##');