擦除两个 for 循环内的矢量元素
Erasing elements of a vector within two for loops
我正在迭代二维数组 (lib) 的行,并将每行的前 4 个条目与包含 4 个元素的元组 (near_pts) 向量进行比较。 基本上,我想从 lib 中提取前 4 个元素(在该行中)与near_pts中的任何元组匹配的所有行,并将这些行添加到新的 2D 数组 (sub_lib)。 lib 或 near_pts 中不应有任何重复。
当 lib 中匹配 near_pts 中的元组时,我想从near_pts中删除它,这样就不会浪费时间尝试匹配该特定元组。 我希望,由于我在擦除后立即有一个中断语句,我们将转到外部 for 循环的下一次迭代,并且 near_pts 上的迭代器将被重置以处理near_pts的修改版本。 但是,这似乎并没有发生,一些元组永远不会匹配(并且应该始终匹配)。我知道这个问题与迭代器有关,因为我的调试工作表明,当多个元素仍然存在时,迭代器有时只循环 1 个元素near_pts,但我无法弄清楚为什么会发生这种情况。 代码如下,如果需要更多信息和/或澄清,请告诉我。
int n = 0;
for (int i=0; i<numPts; i++) {
for (vector<my_tup>::iterator it = near_pts.begin(); it != near_pts.end(); it++) {
bool match = (get<0>(*it)==lib[i][0] && get<1>(*it)==lib[i][1] &&
get<2>(*it)==lib[i][2] && get<3>(*it)==lib[i][3]);
// If there is a match, add it to the sub-library, erase the entry
// from near_pts, and exit the interior loop.
if (match) {
for (int j=0; j<numLibCols; j++) { sub_lib[n][j] = lib[i][j]; }
n++;
near_pts.erase(it);
break;
}
// If we have found all of the tuples, exit the loop.
if (n==near_pts.size()) { break; }
}
}
注意:lib 实际上是一个大小为 numPts x 13 的 2D 数组,near_pts 是 my_tup 的向量,其中 my_tup 是一个元组<双精度、双精度、双精度、双>,sub_lib 是一个大小为 near_pts.size() x 13 的 2D 数组,其中此大小是在擦除near_pts的任何元素之前设置的。
您的最终条件
// If we have found all of the tuples, exit the loop.
if (n==near_pts.size()) { break; }
不正确,因为每场比赛near_pts都会减少,n 会增加。
您可能想检查类似if (near_pts.empty()) break;
在矢量中迭代期间擦除会使迭代器失效,因此您需要更新它。这样做也消除了最后对n
的检查,因为当near_pts
为空时,迭代器必须位于 near_pts.end()
。
int n = 0;
for (int i=0; i<numPts; i++) {
vector<my_tup>::iterator it = near_pts.begin();
while(it != near_pts.end()) {
bool match = (get<0>(*it)==lib[i][0] && get<1>(*it)==lib[i][1] &&
get<2>(*it)==lib[i][2] && get<3>(*it)==lib[i][3]);
// If there is a match, add it to the sub-library, erase the entry
// from near_pts, and exit the interior loop.
if (match) {
for (int j=0; j<numLibCols; j++) { sub_lib[n][j] = lib[i][j]; }
n++;
it = near_pts.erase(it);
break;
}
else {
++it;
}
}
}
使用
near_pts.erase(it);
使it
无效。在此操作之后it
迭代器的任何使用都具有未定义的行为。您可能想使用
near_ptrs.erase(it++);
相反:这样,迭代器it
在擦除之前移出擦除的元素。当然,您不能在使用该语句后无条件地递增it
。
- 擦除while循环中迭代的元素
- C++:如何循环通过向量中的整数元素
- 对于set上的循环-获取next元素迭代器
- 基于范围的 for 循环:迭代使用一个元素扩展的向量
- 如何从使用 for 循环中的矢量大小的矢量中删除元素
- C++基于范围的 for 循环和元素副本
- 这个返回元素位置的基于循环的函数有什么问题?
- 为什么我在尝试在单向链表中打印元素时会出现这个永无止境的循环
- 循环访问还包含未使用元素的字符串数组
- C++用于循环跳过向量的元素?
- 基于相邻元素 c++ 的分段误差范围的循环
- 循环中的变量被设置为下一个数组的元素始终具有相同的内存地址?
- 使用现代C++在 Eigen3 矩阵上使用 for 循环进行元素操作的优雅方式
- 需要帮助编写一个小程序来将循环乘以 n 个元素和 k 个多重性
- C++ 数据结构队列:使用 for 循环查找队列中最大的元素
- 将函数应用于特征矩阵中的所有元素,而无需循环
- 使用 C++ 从每个循环的数组中选择 n 个元素
- 忽略元素的基于范围的 for 循环
- 优先级队列(使用 pairs<int,int> ) 根据 for 循环迭代器的顶级元素
- 用于随机访问和元素循环的最佳数据结构(C++)