Checking if an iterator is valid

huff picture huff · Jan 14, 2010 · Viewed 80k times · Source

Is there any way to check if an iterator (whether it is from a vector, a list, a deque...) is (still) dereferencable, 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 itd points to somewhere meaningful */
if (itd != l.end())
{
    //  blablabla
}

Answer

Jason Govig picture Jason Govig · Jan 14, 2010

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.