c++ - 将元素从 char vector 复制到字符串 vector

标签 c++ vector

我有一个字符 vector ,我想复制字符串 vector 中的元素。我希望第二个 vector 的每个单元格都具有第一个 vector 的 k 元素,形成一个字符串。虽然我没有编译错误,但程序在形成字符串 vector 时崩溃了。

提前致谢!

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

最佳答案

你必须确保你的另一个 vector 中有足够的元素。

(更新:对 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;
}

关于c++ - 将元素从 char vector 复制到字符串 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19579066/

相关文章:

c++ - 共享指针 vector ,清除 vector 后的内存问题

c++ - 将双端队列与 C 库一起使用

c++ - 为什么用于 C++ 中的 sort() 、 max_element() 函数等 STL 函数的 lambda 函数需要两个参数作为输入?

c++ - 如何在 Eclipse 中编译模板类 (C++)?

c++ - OpenGL Alpha channel 细节?

c++ - 数据未按应有的方式使用 lambda 存储在 vector 中

python-3.x - 使用 python 从 netcdf 绘制风向量

c++ - condition_variable::wait_until 意外地通过 g++ (9.4.0)

c++ - 澄清 : What makes 'new' an operator in C++

c++ - 需要帮助理解返回引用的函数