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.
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.
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.
Explanation: Iterators are STL components used to point a memory address of a container. They are used to iterate over container classes.
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:
deque:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With