如何在遍历集合时从集合中删除所有相邻条目。在我的例子中,我有一个自定义比较器,它将相邻条目定义为从左到右相差 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;
}
最佳答案
当谓词为真时继续保存和删除元素的更简单方法。
void remove_adjacent_entries()
{
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()) {
for (auto next = std::next(adjIter); next != mySet.end() && gPred(*adjIter, *next); ++next) {
//save and delete the first of the pair of elements found
adjacentEntries.insert(*adjIter);
mySet.erase(adjIter++);
}
//save and delete the second element
adjacentEntries.insert(*adjIter);
mySet.erase(adjIter++);
}
//print
for(auto& i : adjacentEntries)
std::cout << i << std::endl;
}
关于c++ - 如何在迭代时从集合中删除相邻条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41405716/