2
#include <stdio.h>
#include <iostream>
#include <map>
#include <string>
#include <stdlib.h>

using namespace std;

class Fix
{

};

int main() 
{
    map<int, Fix *> m;

    Fix * f = new Fix();
    m.insert( make_pair( 2, f) );

    m.insert( make_pair( 3, f) );

    map<int, Fix *>::iterator it = m.find(2);
    map<int, Fix *>::iterator it1 = m.find(2);


    m.erase(it);

    // Will Create problem 
    // m.erase(it1);

    // Still value is there
    // So from the map node, iterator copy its value ?
    printf("%d\n", it->first);
    printf("%d\n", it1->first);

}  

I have a Map contains two entries, also two iterators pointing to same entry. Erased one entry from map using Iterator1. Post deletion still Iterator1 and Iterator2 hold value.

Questions

  1. Is Iterator is pointing to the node of Map ( Red Black Tree)
  2. Is Iterator is coping both key and value from the node while it is iterating ? Because of this it holds the value even after entry is deleted from the map.

2 Answers 2

3

For std::map::erase using this method on iterator has the following effects:

  • removes specified elements from the container

  • references and iterators to the erased elements are invalidated. Other references and iterators are not affected.

So you cannot use it1 after you erased it, even though it1 can still point to 'now invalid' previous memory by coincidence.

Sign up to request clarification or add additional context in comments.

Comments

0

please mark the accepted answer.

bits_international is correct in his explanation, change the code in your main function to the following.

map<int, Fix *> m;

Fix * f = new Fix();
m.insert( make_pair( 2, f) );

m.insert( make_pair( 3, f) );

map<int, Fix *>::iterator it = m.find(2);

it = m.erase(it); //you can reuse it after this call
map<int, Fix *>::iterator it1 = m.find(2);

it1 = m.erase(it1); //you can reuse it1 after this call

printf("%d\n", it->first);
printf("%d\n", it1->first);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.