c++ - 如何在迭代时从集合中删除相邻条目

标签 c++ algorithm c++11 stl set

如何在遍历集合时从集合中删除所有相邻条目。在我的例子中,我有一个自定义比较器,它将相邻条目定义为从左到右相差 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/

相关文章:

arrays - 串联排序两个数组的奇怪案例

c++ - 如何在 C++ 模板中使用比较表达式?

c++ - 是否有 C++11 或 Win32 方法来可靠地生成和保存跟踪信息?

c++ - 重新定义符号的算法如何工作?

algorithm - 如何自动完成包含空格的名称?

algorithm - 发现 n! 之间的区别!和一个 2^n 算法

c++ - 在 map 中就地构建不可 move 的对象

c++ - 使用boost精神qi处理gor解析bnf语法的多行规则

c++ - 避免C++虚拟继承

c++ - tensorflow:无效的 fastbin 条目(免费):0x00007f2fa8023940