Reputation: 113
Or hold the return of list.begin ()
to erase the just push_front
ed element later?
Or hold the return of list.end ()
to erase the just push_back
ed element later?
Upvotes: 0
Views: 66
Reputation: 409186
If you're asking if an iterator returned by begin()
will always "point" to the first element, then the answer is no.
An iterator from a list points to the specific node in the list, and if you add more nodes in front the iterator you have will no longer be pointing to the first node, but the same node it always have been pointing to.
If you are asking if an iterator will be invalidated by adding more nodes to the list, then the answer is also no. Like I said in the previous paragraph, iterators points to single nodes, no matter their position in the list. The only way to invalidate an iterator to a list node is to remove the node from the list.
Graphically it could be seen something like this:
You ave a list, and get an iterator to the first node in the list, it would be something like this
+---------+ | begin() |--\ +---------+ \ +--------+ >--> | node 1 | +----------+ / +--------+ | iterator |--/ | node 2 | +----------+ +--------+ | ... | +--------+
Then lest say you add two node in in the front, then it will look like:
+---------+ +------------+ | begin() |-------->| new node a | +---------+ +------------+ | new node b | +----------+ +------------+ | iterator |-------->| node 1 | +----------+ +------------+ | node 2 | +------------+ | ... | +------------+
Upvotes: 1
Reputation: 55887
Yes, you can. Iterators of list are not invalidated after insertion/push_back/push_front.
Upvotes: 1