Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check whether STL iterator points at anything? [duplicate]

Tags:

c++

iterator

stl

Possible Duplicate:
C++ Best way to check if an iterator is valid

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?


1 Answers

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.

like image 182
James Hopkin Avatar answered Sep 15 '25 07:09

James Hopkin