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?

4
  • Deleting entries while iterating is a really bad idea. Commented Jul 12, 2016 at 15:58
  • Is it better in this case to just loop through integers and deleting the ones I wish to delete? Commented Jul 12, 2016 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. Commented Jul 12, 2016 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. Commented Jul 12, 2016 at 16:04

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

4 Comments

Does the erase member function return an iterator? I thought it didn't
@Auclair If you are using a Compiler that supports at least C++ 11 then the erase method returns iterator.
I'm using Visual C++ 2015, so it should support C++11. And your first suggestion worked beautifully, thank you!
@Auclair Yes MS VC++ 2015 is a modern Compiler that supports the C++11

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.