如何在迭代集合時從集中刪除所有相鄰條目。在我的情況下,我有一個自定義比較器,將相鄰條目定義爲從左到右相差1的條目。因此,對於集std::set<int> mySet = {1,2,3,4,5,7,9,10}
我想刪除條目{1,2,3,4,5,9,10}
,因爲這些滿足我的比較。 (注意7是剩下的,因爲它是系列中唯一一個不是相鄰對中的元素之一)如何在迭代時從一組中刪除相鄰條目
下面的代碼(也在coliru)顯示我可以找到正確添加相鄰條目,但是如果我嘗試擦除兩個相鄰一對adjIter
的左側,並且還右側*std::next(adjIter)
代碼崩潰具有無效迭代
int main() {
std::set<int> mySet = {1,2,3,4,5,7,9,10};
static const auto gPred = [](const auto& lhs, const auto& rhs) {
return rhs == lhs+1;
};
auto adjIter = mySet.begin();
std::set<int> adjacentEntries;
while ((adjIter = std::adjacent_find(adjIter, mySet.end(),
gPred)) != mySet.end()) {
adjacentEntries.insert(*adjIter);
// peek at the second entry that should be 1 greater than adjIter
adjacentEntries.insert(*std::next(adjIter));
// how do I erase both *std::next(adjIter) & adjIter
++adjIter;
}
std::cout << adjacentEntries << std::endl;
}
不錯的工作!看起來你是對的,我一直在用這個算法掙扎幾天 – johnco3