How to check whether STL iterator points at anythi

2019-01-19 10:27发布

问题:

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:

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.



回答2:

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();


回答3:

If you want to use iterator in a loop, the safest way to use it is in this fashion:

for (std::vector<int>::iterator it = v.begin(); it != v.end(); ++it)
{
 do_smth();
}


回答4:

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()


标签: c++ stl iterator