1

I'm working with sets for an exercise, and I got an error message I don't know how to interpret. I'm not too savvy with the technical aspects of programming. I'm a math student, so I have only really focused on the actual programming itself, so certain errors I just don't know how to handle.

I made the set and inserted every integer from 0 to 100 with the endpoints. I then wanted to erase every integer divisible by 2 except 2 itself. Here's the code:

set<int> intSet;
for (int i = 0; i < 101; i++) {
    intSet.insert(i);
}

for (set<int>::iterator twoDivIt = intSet.begin(); twoDivIt != intSet.end(); twoDivIt++) {
    if (*twoDivIt % 2 == 0) {
        if (*twoDivIt == 2) {
            continue;
        }
        else {
            intSet.erase(twoDivIt);
        }
    }
}

for (set<int>::iterator it = intSet.begin(); it != intSet.end(); it++) {
    std::cout << *it << "\t";
}

I get a popup window telling me the debuc assertion failed, and that "map/set iterator not incrementable". What have I done wrong?

Auclair
  • 125
  • 1
  • 10
  • Deleting entries while iterating is a really bad idea. – tkausl Jul 12 '16 at 15:58
  • Is it better in this case to just loop through integers and deleting the ones I wish to delete? – Auclair Jul 12 '16 at 15:59
  • Why do you even add all the integers? Instead of adding all and removing the even ones you could just add only the odd ones. – tkausl Jul 12 '16 at 16:01
  • @tkausl Yes of course, that's what I would do if this was for an actual program. It's the explicit wish of the exercise though ;) It's just so we can learn how to use sets. – Auclair Jul 12 '16 at 16:04

1 Answers1

0

The loop should look like

for ( std::set<int>::const_iterator twoDivIt = intSet.begin(); twoDivIt != intSet.end(); ) 
{
    if ( *twoDivIt % 2 == 0 && *twoDivIt != 2 ) twoDivIt = intSet.erase( twoDivIt );
                                                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    else ++twoDivIt;
}

If the Compiler does not support the C++11 then the loop can look like

for ( std::set<int>::const_iterator twoDivIt = intSet.begin(); twoDivIt != intSet.end(); ) 
{
    if ( *twoDivIt % 2 == 0 && *twoDivIt != 2 ) intSet.erase( twoDivIt++ );
    else ++twoDivIt;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335