将std :: string转换为std :: vector< char> [英] Converting std::string to std::vector<char>
问题描述
我使用的库接受数据作为向量的
char
。我需要传递字符串
到库。
I am using a library which accepts data as a vector
of char
s. I need to pass a string
to the library.
我想使用 std: :vector
构造函数,它接受迭代器来执行转换 - 但是想知道是否有更好的方法。
I think about using std::vector
constructor which accepts iterators to carry out the conversion - but wondered if there is a better way of doing it?
/*Note: json_str is of type std::string*/
const std::vector<char> charvect(json_str.begin(), json_str.end());
推荐答案
不,这是方法,直接初始化
Nope, that's the way to do it, directly initializing the vector with the data from the string.
由于@ildjarn在他的评论中指出,如果无论什么原因你的数据缓冲区需要以null结束,你需要显式添加 charvect.push_back('\0')
。
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')
.
重用缓冲区,使用需要迭代器的分配
成员函数。
Also note, if you want to reuse the buffer, use the assign
member function which takes iterators.
这篇关于将std :: string转换为std :: vector< char>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!