How to copy std::string into std::vectorlt;chargt;?(如何将 std::string 复制到 std::vectorchar 中?)
问题描述
可能的重复:
将 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));
这篇关于如何将 std::string 复制到 std::vector<char> 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何将 std::string 复制到 std::vector<char> 中?


- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- C++ 协变模板 2021-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 静态初始化顺序失败 2022-01-01
- 近似搜索的工作原理 2021-01-01
- 从python回调到c++的选项 2022-11-16
- 使用/clr 时出现 LNK2022 错误 2022-01-01