c++ - 复制向量元素到其他其他向量*(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)。
解决方案
所以在这里我尝试修复你的代码,虽然我仍然不知道你到底在做什么。我假设您需要在另一个向量的给定索引处插入另一个向量元素。一旦您说出确切的要求,就可以进行相应的修改:
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
推荐阅读
- ecmascript-6 - JSDoc 在带有 Rollup 的 .MJS 文件中不起作用
- python - 如何间隔 2 分钟运行 100 个 python 文件?
- python - Python 局部变量范围
- c - 为什么将指向字符串值的指针更改为另一个字符串有效,但不能直接更改字符串的值?
- php - 在 Mac Catalina 上安装 V8JS
- swift - Swift 构建中的类型检查规则?
- git - 在不克隆存储库的情况下获取 .git 目录
- server - 使用 ESP 01 AT 命令向服务器发送数据的正确方法
- unit-testing - 我应该如何处理使用 runtime.GOOS 的 Go 函数的测试?
- python - Flask 登录“current_user”会话已过期