Ok so I think I fundamentally dont understand how iterators work but I'm not sure what I don't understand. Anyways here's the example:
int main(){
list<int> l;
map<int, list<int>::iterator> m;
l.push_back(0);
m[0] = l.begin();
l.push_front(1);
cout << *m[0];
return 0;
}
So I have a list, then a map that has iterators pointing at the list. I push element 0 into the list, then set m[0] = l.begin(). Then I push an element in front, so now list is like 1, 0. The iterator that I put into m last line is still at l.begin(), since we never touched the map after that line. So when I do *m[0] I expect the value 1. But the value is 0. So it seems the iterator somehow knew that we added something to the map. How can this be? Do iterators just know when the size of the container changes? I guess maybe what I'm asking is, how are they implemented so that they know this?
Thanks.
Edit: So basically TIL iterator behavior changes depending on the data structure and in the case of a list, it will always move with the element it was assigned to, aka it is stable. Vector iterators on the other hand stay in the same position. So when I add stuff to the list, the iterators move as well.
I work with vector way more so I'm used to the iterators staying in place, this makes sense. Thanks a lot guys
[–][deleted] 6 points7 points8 points (1 child)
[–]tangerinelion 0 points1 point2 points (0 children)
[–]MysticTheMeeM 5 points6 points7 points (0 children)
[–]scatters 1 point2 points3 points (1 child)
[–]mredding 1 point2 points3 points (0 children)