C++ 如何将 std::string 复制到 std::vector<char> 中?

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

How to copy std::string into std::vector<char>?

c++stringvectorcopy

提问by myWallJSON

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

可能的重复:
将 std::string 转换为 std::vector<char>

I tried:

我试过:

std::string str = "hello";
std::vector<char> data;
std::copy(str.c_str(), str.c_str()+str.length(), data);

but it does not work=( So I wonder How to copy std::stringinto std::vector<char>or std::vector<uchar>?

但它不起作用=(所以我想知道如何复制std::stringstd::vector<char>std::vector<uchar>

回答by R. Martinho Fernandes

std::vectorhas a constructor that takes two iterators. You can use that:

std::vector有一个带有两个迭代器的构造函数。你可以使用它:

std::string str = "hello";
std::vector<char> data(str.begin(), str.end());

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));

回答by dasblinkenlight

You need a back inserter to copy into vectors:

您需要一个后置插入器来复制到向量中:

std::copy(str.c_str(), str.c_str()+str.length(), back_inserter(data));