簡體   English   中英

在兩個for循環內擦除向量的元素

[英]Erasing elements of a vector within two for loops

我在2D數組(lib)的行上進行迭代,並將每行的前4個條目與包含4個元素的元組(near_pts)的向量進行比較。 基本上,我想從lib中提取所有行,其中前4個元素(在該行中)與near_pts中的任何元組匹配,並將這些行添加到新的2D數組(sub_lib)中。 lib或near_pts中不應有任何重復。

當lib中的near_pts中的元組被匹配時,我想從near_pts中刪除它,這樣就不會浪費時間嘗試匹配該特定的元組。 我希望,因為在擦除后立即有一個break語句,所以我們將轉到外部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是tuple <double,double,double,double>的元組,sub_lib是大小為near_pts.size()x的2D數組13,在擦除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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM