在遍历集合时如何擦除集合中的所有相邻条目。在我的情况下,我有一个自定义比较器,该比较器将相邻条目定义为从左到右相差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;
}
在谓词为true时继续保存和删除元素的更简单方法。
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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句