Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 902
PypeBros Avatar asked Apr 17 '09 06:04

PypeBros


People also ask

What is iterators in C?

An iterator is an object that allows you to step through the contents of another object, by providing convenient operations for getting the first element, testing when you are done, and getting the next element if you are not. In C, we try to design iterators to have operations that fit well in the top of a for loop.

What are the STL iterators and what is their purpose?

Iterators are used to point at the memory addresses of STL containers. They are primarily used in sequences of numbers, characters etc. They reduce the complexity and execution time of the program.

What are iterators iterators are used to?

Explanation: Iterators are STL components used to point a memory address of a container. They are used to iterate over container classes.


1 Answers

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.
like image 167
aJ. Avatar answered Nov 15 '22 16:11

aJ.