Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
457 views
in Technique[技术] by (71.8m points)

stl - What is the lifetime and validity of C++ iterators?

I'm planning to implement a list of Things in C++ where elements might be removed out of order. I don't expect that i'll need any kind of random access (i just need to sweep the list periodically), and the order of items isn't important either.

So I thought of std::list<Thing*> with this->position = insert(lst.end(), thing) should do the trick. I'd like the Thing class to remember the position of each instance so that i can later easily do lst.erase(this->position) in constant time.

However, i'm still a bit new to C++ STL containers, and i don't know if it's safe to keep iterators for such a long time. Especially, given that there will be other elements deleted ahead and after the inserted Thing before it's gone.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In list all iterators remain valid during inserting and only iterators to erased elements get invalid during erasing.

In your case keeping iterator should be fine even when other elements deleted ahead and after the inserted Thing*.

EDIT:

Additional details for vector and deque:

Vector:

  • inserting --- All iterators get invalid if reallocation happens, otherwise its valid.
  • erasing ---- All iterators after erase point get invalid.

deque:

  • inserting --- All iterators get invalid.
  • erasing ---- All iterators get invalid.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...