Hi,
can you explain the life cycle of an iterator ?

pls consider following example.

typedef map<int, int> mapii;
typedef map<int, int>::iterator itii;


mapii m;
pair<itii, bool> p = m.insert(make_pair(1, 2));
itii it = p.first;


// do all sorts of insert/erase to map
// but dont remove pair(1,2)
m.insert(0, 1);
m.insert(2, 3);
m.insert(3, 4);
// so the map would be
// 0,1
// 1,2   <-- we are looking at here
// 2,3
// 3,4

// do some erases
m.erase(2);
m.erase(0);
// so the map would be
// 1,2   <-- we are looking at here
// 3,4


// do some inserts
m.insert(-1, 0);
m.insert(0, 1);
m.insert(5, 6);
// so the map would be
// -1,0
// 0,1
// 1,2   <-- we are looking at here
// 3,4
// 5,6



// now we are going to remove 'it' which we kept safely
m.erase(it);
// so the map would be
// -1,0
// 0,1
// 3,4
// 5,6


this works as expected. but can this be guarenteed.
eg. if i do all sorts of manipulations for the map without touching
the iterator would it last ?

one more thing. the iterator is a local variable. map returns an
iterator on insert (not a reference to an iterator). so is what i'm
doing correct? can the iterator be treated like a pointer. i tried
with moving the local iterator around functions eg. returning
iterator. it works like a pointer as i understood.

thanks.



Reply via email to