迭代一对对和擦除元素

时间:2018-03-26 15:45:38

标签: c++ for-loop set erase

我得到运行时错误,我怀疑是因为这段代码,我想知道如何迭代一组并从中间擦除它。

    for (auto it : a) {
        if (freq[it.first] == 1 || freq[it.second] == 1)
            a.erase(it);
    }

我尝试了这个解决方案,我在另一个问题上找到了它,但它似乎仍然无效:

    for (set<pair<int, int> >:: iterator it = a.begin(); it != a.end();)
    {
        cout << it->first << " " << it->second << endl;
        if (freq[it->first] == 1 || freq[it->second] == 1)
        {
            removed = true;
            a.erase(it);
        }
        else
        {
            ++it;
        }
    }

1 个答案:

答案 0 :(得分:0)

这解决了它:

for (set<pair<int, int> >:: iterator it = a.begin(); it != a.end();/* blank */)
{
    cout << it->first << " " << it->second << endl;
    if (freq[it->first] == 1 || freq[it->second] == 1)
    {
        removed = true;
        it = a.erase(it);
    }
    else
    {
        ++it;
    }
}