Safe to store list::iterator for later use?

来源:互联网 发布:光伏数据采集器接法 编辑:程序博客网 时间:2024/06/05 22:49

转自: https://stackoverflow.com/questions/837267/safe-to-store-listiterator-for-later-use


===========================Ask======================================

Suppose I have a list, in which no new nodes are added or deleted. However, the nodes may be shuffled around.

Is it safe to save an iterator, pointing to a node in the list, and access it at some arbitrarily later time?

Edit (followup question): The documentation for list::splice() says that it removes elements from the argument list. Does this mean if I call splice, using the same list as arguments to the function, that existing iterators will be invalidated?


===========================Answer1===================================

Yes, std::list iterators are just pointers to a node. You can insert, delete (other nodes), and rearrange nodes in the list and the iterator is not invalidated.


===========================Answer2===================================

Yes.
The standard grantees that iterators into a list will not be invalidated unless the item, they point at (metaphorically speaking) is removed from the list.

From this page: http://www.sgi.com/tech/stl/List.html

Lists have the important property that insertion and splicing do notinvalidate iterators to list elements, and that even removal invalidatesonly the iterators that point to the elements that are removed.