views:

2857

answers:

5

I want to do something like this:

std::vector<int>::iterator it;
// /cut/ search for something in vector and point iterator at it. 
if(!it) //check whether found
    do_something();

But there is no operator! for iterators. How can I check whether iterator points at anything?

+14  A: 

You can't. The usual idiom is to use the container's end iterator as a 'not found' marker. This is what std::find returns.

std::vector<int>::iterator i = std::find(v.begin(), v.end(), 13);
if (i != v.end())
{
     // ...
}

The only thing you can do with an unassigned iterator is assign a value to it.

James Hopkin
You covered the case when the iterator is initialized and still valid. However, some operations on some containers may invalidate the iterators. For example, removal of elements from a vector may invalidate iterators ( the iterator pointing to the last element in the vector in this case).
Cătălin Pitiș
@Cătălin: that's all true, but out of the scope of the question, I think. Just as the ! (`not`) operator will only work with valid or null pointers, the above will only work with valid iterators (including `end` iterators).
James Hopkin
A: 

Use iterator only in for/while-loops like this for (std::vector::iterator it = v.begin(); it != v.end(); ++it) { do_smth(); }

Xeningem
Actually many standard algorithms return iterators (e.g. find) and methods on containers (e.g. map::find)
1800 INFORMATION
+1  A: 

Though the iterators are considered as general form of pointers, they are not exactly the pointers. The standard defines Past-the-end iterator to indicate the search failure in containers. Hence, it is not recommended to check the iterators for NULL

Past-the-end values are nonsingular and nondereferenceable.

if(it != aVector.end())  //past-the-end iterator
    do_something();
aJ
+1  A: 

Hope this help : Is there any way to check if an iterator is valid?

lsalamon
A: 

I believe this should generally give you a good test:

if (iterator._Mycont == &MyContainer) { Probably a valid iterator! }

You could do tests to make sure that the iterator does not equal the end...

iterator != MyContainer.end()

and:

iterator >= MyContainer.begin()

Seems extremely compiler (and version!) dependent.
Mark Ransom