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

How to copy std::string into std::vectorlt;chargt;?(如何将 std::string 复制到 std::vectorchar 中?)
本文介绍了如何将 std::string 复制到 std::vector<char> 中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

可能的重复:
将 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> 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)
STL BigInt class implementation(STL BigInt 类实现)
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)