Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing iterators inside containers

Tags:

c++

iterator

stl

I am building a DLL that another application would use. I want to store the current state of some data globally in the DLL's memory before returning from the function call so that I could reuse state on the next call to the function.

For doing this, I'm having to save some iterators. I'm using a std::stack to store all other data, but I wasn't sure if I could do that with the iterators also.

Is it safe to put list iterators inside container classes? If not, could you suggest a way to store a pointer to an element in a list so that I can use it later?

I know using a vector to store my data instead of a list would have allowed me to store the subscript and reuse it very easily, but unfortunately I'm having to use only an std::list.

like image 742
Sahas Avatar asked Nov 30 '22 12:11

Sahas


2 Answers

Iterators to list are invalidated only if the list is destroyed or the "pointed" element is removed from the list.

like image 102
AProgrammer Avatar answered Dec 05 '22 05:12

AProgrammer


Yes, it'll work fine.

Since so many other answers go on about this being a special quality of list iterators, I have to point out that it'd work with any iterators, including vector ones. The fact that vector iterators get invalidated if the vector is modified is hardly relevant to a question of whether it is legal to store iterators in another container -- it is. Of course the iterator can get invalidated if you do anything that invalidates it, but that has nothing to do with whether or not the iterator is stored in a stack (or any other data structure).

like image 41
jalf Avatar answered Dec 05 '22 04:12

jalf