How to verify that an STL iterator points to something?

Possible duplicate:
C ++ Best way to check if an iterator is really

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 no operator! for iterators. How can I check if an iterator points to anything?

+22
c ++ iterator stl
May 05 '09 at 9:56 a.m.
source share
4 answers

You can not. A common idiom is to use the final container 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 to assign a value to it.

+45
May 05 '09 at 9:58 a.m.
source share

Although iterators are considered the general form of pointers, they are not exactly pointers. The standard defines a Past-the-end iterator to indicate a container search error. Therefore, it is not recommended to check iterators for NULL

Past-the-end values ​​are nonsingular and inexpressible.

 if(it != aVector.end()) //past-the-end iterator do_something(); 
+2
May 05 '09 at 10:08
source share

If you want to use an iterator in a loop, the safest way to use it is as follows:

 for (std::vector<int>::iterator it = v.begin(); it != v.end(); ++it) { do_smth(); } 
+1
May 05 '09 at 10:02
source share

I believe this should give you a good test:

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

You can do tests to make sure the iterator is not equal to the end ...

 iterator != MyContainer.end() 

and

 iterator >= MyContainer.begin() 
-3
Jun 04 '09 at 18:28
source share



All Articles