Is there any way to check if an iterator (whether it is from a vector, a list, a deque...) is (still) dereferenceable, i.e. has not been invalidated?
I have been using try
-catch
, but is there a more direct way to do this?
Example: (which doesn't work)
list<int> l; for (i = 1; i<10; i++) { l.push_back(i * 10); } itd = l.begin(); itd++; if (something) { l.erase(itd); } /* now, in other place.. check if it points to somewhere meaningful */ if (itd != l.end()) { // blablabla }
use erase with increment : if (something) l. erase(itd++); so you can test the validity of the iterator.
Iterator invalidation is what happens when an iterator type (an object supporting the operators ++ , and * ) does not correctly represent the state of the object it is iterating.
No, you can't check against NULL because it is not a pointer. Return and also check against animalList. end() . Only when the iterator is not equal to end() should you dereference it.
Every iterator and reference after the point of erasing is invalidated. Only the iterators and references to the erased element is invalidated.
I assume you mean "is an iterator valid," that it hasn't been invalidated due to changes to the container (e.g., inserting/erasing to/from a vector). In that case, no, you cannot determine if an iterator is (safely) dereferencable.
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