0

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();
  }
Aneesh Narayanan
  • 3,220
  • 11
  • 31
  • 48
  • You should try to add some debug `cout`s in your code to help trace down your problem. We typically do not debug your code for you. Identify the problem and then ask the question. –  Mar 15 '12 at 12:01
  • i am getting a run time error in this part m1_cIter = m1.begin( ); m1_cIter--; m1.erase ( m1_cIter ); – Aneesh Narayanan Mar 15 '12 at 12:07
  • http://stackoverflow.com/questions/4885318/calling-erase-with-iterator-vs-const-iterator –  Mar 15 '12 at 12:34

3 Answers3

2

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.

Filip Roséen - refp
  • 62,493
  • 20
  • 150
  • 196
  • @0A0D but not a `const_iterator`. a `const_iterator` should/cannot be used to modify the element inside a container. – Filip Roséen - refp Mar 15 '12 at 12:23
  • Yes, but there is a workaround. It's a defect in the language itself. http://stackoverflow.com/questions/4885318/calling-erase-with-iterator-vs-const-iterator –  Mar 15 '12 at 12:30
1
m1_cIter = m1.begin();
m1_cIter --;

is undefined behavior. Did you mean

m1_cIter = m1.end();
m1_cIter --;
James Kanze
  • 150,581
  • 18
  • 184
  • 329
0

m1.erase ( m1_cIter );

This could be the problem because m1_cIter is a const_iterator. The code will not compile.

After commenting this line, I get this output:

 ./maptest
The value of the last element of m1 is:
30
The value of the last element of m1 is now:
20

Also in your code:

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

This could be undefined behavior, not guaranteed to work always.

Sanish
  • 1,699
  • 1
  • 12
  • 21