首页 > 解决方案 > 复制向量元素到其他其他向量*(1作为指针传递)

问题描述

void check_and_fix_problems(vector<string>* fileVec, int index) {

    vector<string> q = { "something", "else", "here" };

    q.insert(q.end(), fileVec->begin() + index + 2, fileVec->end()); //add at the end of q vector the fileVec vector

    for (int f = 0; f < q.size(); f++) {//here is the problem/s
        std::copy(q.at(f).begin(), q.at(f).end(), fileVec->at(f)); //copy q vector to fileVec
        //fileVec->at(f) = q.at(f);
    }
}

我对这段代码有疑问,当我调用它时,我得到 fileVec 向量超出范围的运行时错误(我猜是因为 q 向量的元素比 fileVec 多,所以一些索引超出范围)但是我如何增加向量向量的大小通过他们的指针?

并且在这里使用 std::copy 也很重要,或者我可以简单地对 fileVec->at(f) = q.at(f); 做同样的事情?(因为我知道,当此函数返回时,函数中的所有内容都将被删除,结果将是 fileVec 中的所有元素显示在 nullptr)。

标签: c++arraysvectorstd

解决方案


所以在这里我尝试修复你的代码,虽然我仍然不知道你到底在做什么。我假设您需要在另一个向量的给定索引处插入另一个向量元素。一旦您说出确切的要求,就可以进行相应的修改:

void check_and_fix_problems(std::vector<string> &fileVec, int index) {

    std::vector<string> q = { "something", "else", "here" };

    q.insert(q.end(), fileVec.begin() + index + 2, fileVec.end()); //add at the end of q vector the fileVec vector

    //for debugging purpose
    std::cout << "q in function contains:";
    for (std::vector<string>::iterator it = q.begin() ; it < q.end(); it++)
        std::cout << ' ' << *it;
    std::cout << '\n';

    //vector<string>::iterator itr;
    // for (itr = q.begin(); itr != q.end(); itr++) {//here is the problem/s
    //     fileVec.insert(fileVec.begin() + index,*itr); //copy q vector to fileVec
    //     //fileVec->at(f) = q.at(f);
    // }
    fileVec.insert(fileVec.begin() + index, q.begin(),q.end());
}

int main ()
{
    std::vector<string> a = {"xyz","abc","says","hello"};
    check_and_fix_problems(a, 1);
    std::cout << "a contains:";
    for (std::vector<string>::iterator it = a.begin() ; it < a.end(); it++)
        std::cout << ' ' << *it;
    std::cout << '\n';
    return 0;
}

这给出了以下输出:

q in function contains: something else here hello
a contains: xyz something else here hello abc says hello

推荐阅读