1

I am trying to delete some elements from an std::map. In particular the elements that have

value = 100

should be deleted. However after running the following piece of code a bug occurs. An element with value 100 appears in the remaining map, after the erase(it) method. Where is the bug?

Code:

#include <iostream>
#include <map>

int main() {
    std::map<int, int> outcomes;
    outcomes.clear();

    if ( !outcomes.insert( std::make_pair( 10, 1 ) ).second ) 
        return 0;
    if ( !outcomes.insert( std::make_pair( 11, 100 ) ).second ) 
        return 0;
    if ( !outcomes.insert( std::make_pair( 12, 100 ) ).second ) 
        return 0;
    if ( !outcomes.insert( std::make_pair( 13, 100 ) ).second ) 
        return 0;
    if ( !outcomes.insert( std::make_pair( 14, 100 ) ).second ) 
        return 0;
    if ( !outcomes.insert( std::make_pair( 15, 101 ) ).second ) 
        return 0;
    if ( !outcomes.insert( std::make_pair( 16, 101 ) ).second )
        return 0;
    if ( !outcomes.insert( std::make_pair( 17, 100 ) ).second )
        return 0;

    std::map<int, int>::iterator it = outcomes.begin();
    while(it != outcomes.end())
    {
        std::cout<<it->first<<" :: "<<it->second<<std::endl;
        it++;
    }

    it = outcomes.begin();
    while(it != outcomes.end())
    {
        if( it->second == 100 )
            outcomes.erase(it);
        it++;
    }
    std::cout << "after delete" << std::endl;
    it = outcomes.begin();
    while(it != outcomes.end())
    {
        std::cout<<it->first<<" :: "<<it->second<<std::endl;
        it++;
    }
    return 0;
}  

Result is the following:

10 :: 1
11 :: 100
12 :: 100
13 :: 100
14 :: 100
15 :: 101
16 :: 101
17 :: 100
after delete
10 :: 1
14 :: 100
15 :: 101
16 :: 101
cateof
  • 6,608
  • 25
  • 79
  • 153

0 Answers0