将 Vector<String > 元素复制到其他 Vector<String>* (1 作为

copy a vector<string> elements to other other vector<string>* (1 passing as pointer)

本文关键字:gt Vector String lt 作为 元素 复制 其他      更新时间:2023-10-16
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 处(。

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

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