T.L
T.L

Reputation: 113

Can I hold the iterator of a new inserted element of a std::list and use the iterator to erase the element later safely?

Or hold the return of list.begin () to erase the just push_fronted element later?

Or hold the return of list.end () to erase the just push_backed element later?

Upvotes: 0

Views: 66

Answers (2)

Some programmer dude
Some programmer dude

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

ForEveR
ForEveR

Reputation: 55887

Yes, you can. Iterators of list are not invalidated after insertion/push_back/push_front.

Upvotes: 1

Related Questions