mardi 13 avril 2021

Why can't I erase a set element without using an iterator? [duplicate]

I am trying to delete odd numbers in a set. I can't seem to do it without having to use an iterator. My compiler throws an error. Please help!

This works:

void remove_odd(set<int> &s) {
    //set<int>::iterator it;
    for (auto it = s.begin(); it != s.end(); ) {
        if (*it % 2 == 1) {
            s.erase(it++); 
        }
        else {
            it++;
        }
    }
}

this doesn't work:

void remove_odd(set<int> &s) {
    for (int item: s) {
        if (item % 2 == 1)
            s.erase(item);
    }
}

Aucun commentaire:

Enregistrer un commentaire