迭代一组对并擦除元素

Iterating over a set of pairs and erasing elements

我收到 运行-time 错误,我怀疑是因为这段代码,我想知道如何迭代一个集合并在中间从中删除。

    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;
        }
    }

这解决了它:

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;
    }
}