将元素从字符向量复制到字符串向量

Copying elements from a char vector to a string vector

本文关键字:向量 复制 字符串 字符 元素      更新时间:2023-10-16

我有一个字符向量,我想复制字符串向量中的元素。我希望第二个向量的每个单元格都有第一个向量的 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);