Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if an iterator is valid

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 } 
like image 702
huff Avatar asked Jan 14 '10 08:01

huff


People also ask

How do I know if my iterator is valid?

use erase with increment : if (something) l. erase(itd++); so you can test the validity of the iterator.

What is an invalid 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.

How do I check if an iterator is not null?

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.

Is iterator valid after erase?

Every iterator and reference after the point of erasing is invalidated. Only the iterators and references to the erased element is invalidated.


1 Answers

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.

like image 131
Jason Govig Avatar answered Oct 02 '22 20:10

Jason Govig