擦除两个 for 循环内的矢量元素

Erasing elements of a vector within two for loops

本文关键字:元素 循环 for 两个 擦除      更新时间:2023-10-16

我正在迭代二维数组 (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