Checking if an iterator is valid


Question

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
}
1
62
1/22/2013 8:33:46 AM

Accepted Answer

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.

59
1/14/2010 8:37:10 AM

As jdehaan said, if the iterator wasn't invalidated and points into a container, you can check by comparing it to container.end().

Note, however, that if the iterator is singular -- because it wasn't initialized or it became invalid after a mutating operation on the container (vector's iterators are invalidated when you increase the vector's capacity, for example) -- the only operation that you are allowed to perform on it is assignment. In other words, you can't check whether an iterator is singular or not.

std::vector<int>::iterator iter = vec.begin();
vec.resize(vec.capacity() + 1);
// iter is now singular, you may only perform assignment on it,
// there is no way in general to determine whether it is singular or not

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon