如何将 std::string 复制到 std::vector<char> 中?
可能的重复:
将 std::string 转换为 std::vector
我试过了:
std::string str = "hello";
std::vector<char> data;
std::copy(str.c_str(), str.c_str()+str.length(), data);
但它不起作用=(所以我想知道如何将 std::string
复制到 std::vector<char>
或 std::vector<uchar>
?
but it does not work=( So I wonder How to copy std::string
into std::vector<char>
or std::vector<uchar>
?
推荐答案
std::vector
有一个带有两个迭代器的构造函数.你可以使用它:
std::vector
has a constructor that takes two iterators. You can use that:
std::string str = "hello";
std::vector<char> data(str.begin(), str.end());
如果你已经有一个vector,并且想在最后添加字符,你需要一个back inserter:
If you already have a vector and want to add the characters at the end, you need a back inserter:
std::string str = "hello";
std::vector<char> data = /* ... */;
std::copy(str.begin(), str.end(), std::back_inserter(data));
相关文章