Search code examples
c++dictionaryerase

map erase error


i have wriitten program for diffrent operations on maps.

and a sample code of my program is given below.

while running this code i am getting an error like map erase out of range exception.

please help me to solve this.

  int main( )
  {
    using namespace std;
    map <int, int> m1;

    map <int, int> :: iterator m1_Iter;
    map <int, int> :: const_iterator m1_cIter;
    typedef pair <int, int> Int_Pair;

    m1.insert ( Int_Pair ( 1, 10 ) );
    m1.insert ( Int_Pair ( 2, 20 ) );
    m1.insert ( Int_Pair ( 3, 30 ) );

    m1_cIter = m1.end( );
    m1_cIter--;
    cout << "The value of the last element of m1 is:\n" 
      << m1_cIter -> second << endl;

    m1_Iter = m1.end( );
    m1_Iter--;
    m1.erase ( m1_Iter );

            m1_cIter = m1.begin( );
    m1_cIter--;
    m1.erase ( m1_cIter );

    m1_cIter = m1.end( );
    m1_cIter--;
    cout << "The value of the last element of m1 is now:\n"
      << m1_cIter -> second << endl;
    getchar();
  }

Solution

  • You are trying to erase the element located before your first element, what would this point to?


    Relevant snippet from posted code:

     m1_cIter = m1.begin( );
     m1_cIter--;
     m1.erase ( m1_cIter );
    

    A side note is that I'm finding it quite odd that you are able to compile and run the provided snippet at all.

    It should give you errors regarding the fact that you cannot erase an element through a std::map<int,int>::const_iterator, which is the type of m1_cIter.