简体   繁体   English

"将 std::string 转换为 std::vector<char>"

[英]Converting std::string to std::vector<char>

I am using a library which accepts data as a vector<\/code> of char<\/code> s.我正在使用一个接受数据作为char<\/code> vector<\/code>的库。 I need to pass a string<\/code> to the library.我需要将一个string<\/code>传递给库。

I think about using std::vector<\/code> constructor which accepts iterators to carry out the conversion - but wondered if there is a better way of doing it?我考虑使用接受迭代器的std::vector<\/code>构造函数来执行转换 - 但想知道是否有更好的方法来做到这一点?

/*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.不,这就是这样做的方法,直接用字符串中的数据初始化向量。

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 assign member function which takes iterators.另请注意,如果您想重用缓冲区,请使用带有迭代器的assign成员函数。

Your method of populating the vector is 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 string in to the vector<char> .您也可以简单地将string的内容复制到vector<char> This is going to be most useful when you either have a vector already instantiated, or if you want to append more data to the end -- or at any point, really.当您已经实例化了一个vector ,或者如果您想在末尾附加更多数据时,这将是最有用的 - 或者在任何时候,真的。

Example, where s is a std::string and v is a std::vector<char> :示例,其中sstd::stringvstd::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('\0');

An alternative that might be worth considering if you need the terminating null is:如果您需要终止 null,则可能值得考虑的替代方法是:

std::vector<char> charvect(json_str.c_str(), json_str.c_str() + json_str.size() + 1); 

and if charvect already exists you can do:如果charvect已经存在,你可以这样做:

charvect.assign(json_str.c_str(), json_str.c_str() + json_str.size() + 1);

This might be quicker than doing a push_back('\\0') particularly if the push_back triggers a memory reallocation.这可能比执行push_back('\\0')更快,特别是如果 push_back 触发内存重新分配。

You can do it in this way.你可以这样做。

  std::string s = "Hello World!";
    std::vector<char> v(s.begin(), s.end());
    for (const char &c: v)
        std::cout << c;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM