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);来做同样的事情? (因为据我所知,当此函数返回时,该函数中的所有内容都将被删除,结果将是在nullptr中显示的fileVec中的所有元素。)
答案 0 :(得分:0)
所以在这里我尝试修复您的代码,尽管我仍然不知道您到底在做什么。我假设您需要在另一个向量的给定索引处插入另一个向量元素。告诉您确切的要求后,即可对其进行相应的修改:
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