将元素从字符向量复制到字符串向量
Copying elements from a char vector to a string vector
我有一个字符向量,我想复制字符串向量中的元素。我希望第二个向量的每个单元格都有第一个向量的 k 个元素,形成一个字符串。虽然我没有编译错误,但程序在形成字符串向量时崩溃。
提前感谢!
vector<string> v2;
for(int i = 0; i <= v1.size(); i++){ //v1 is the char vector
for(int j = 0; j <= k; j++){
v2[i] = v2[i] + v1[j];
}
cout << v2[i] << endl;
}
你必须确保你的另一个向量中有足够的元素。
(更新:对 v2 使用后缀操作将节省内存和运行时间,因为在这种情况下,无需分配临时变量来执行加法操作。
vector <string> v2(v1.size());
for(int i=0;i<=v1.size();i++){ //v1 is the char vector
for (int j=0;j<=k;j++){
v2[i]+=v1[j];
}
cout<<v2[i]<<endl;
}
当您
访问v2[i]
时,您的向量v2
为空:因此,此操作是非法的。你可能想要类似的东西
std::vector<std::string> v2;
v2.reserve(v1.size()); // optionally reserve enough elements; may improve performance
for (std::string::const_iterator it(v1.begin()), end(v1.end()); it != end; ++it) {
v2.push_back(std::string(it, it + std::min(k, std::distance(it, end))));
std::cout << v2.back() << 'n';
}
有一个字符串构造函数需要一对迭代器 - 使用它来获取k
连续字符。 然后,从最后一个字符串结束的下一个字符串开始(我认为这就是你的问题的意思?
vector<string> v2;
auto p1 = v1.begin();
auto const pend = v1.end();
if (v1.size() > k) {
auto const pendk = pend - k;
do {
auto const p2 = p1 + k; // locate k characters
v2.emplace_back(p1, p2);// make a string from those characters
p1 = p2; // the end of this one is the start of the next
} while (p1 < pendk);
}
if (p1 != pend) // deal with any leftover (<= k) characters at the end
v2.emplace_back(p1, pend);
相关文章:
- 将指向给定子类的指针从一个向量复制到另一个向量
- 将字符向量复制到另一个向量
- 将shared_ptr的向量复制到抽象基的派生类
- 将一种数据类型的向量复制到同一数据类型的结构向量中的有效方法是什么
- 自定义类对象的C++向量 - 复制构造函数已删除 - std::ifstream
- 如何在C++中将一个对象从一个向量复制到另一个向量?
- 将特征向量复制到 C 数组
- 将std ::向量复制到CV :: Mat_的行操作相同
- 将向量复制到 std::string
- 如何以相反的顺序将整个向量复制到队列中
- 按索引将类类型元素从一个向量复制到另一个 c++
- 使用迭代器将向量复制到数组中
- 为什么是非法的:将指针向量复制到指向常量的指针向量中
- 将元素从一个向量复制到另一个向量的最有效方法,给定一个不被复制的索引列表
- C++-将数据从浮点向量复制到uint8向量
- 将字符串从向量复制到字符串
- 我可以使用STD ::复制将数据的位模式从整数向量复制到一系列未签名的字符
- 将指针从一个向量复制到另一个向量;地址指出了变化
- 如何将内容从一个字符串向量复制到另一个字符串向量
- 以相反的顺序将一个向量复制到另一个向量