I’d like to find out if a vector of pointers contains an entry that is NULL, preferably using code in the STL and not writing a loop. I’ve tried this expression:
std::find(dependent_events.begin(), dependent_events.end(), NULL)
But I get errors telling me that I have a “comparison between a pointer and an integer.” Is there a better way to do this?
NULLin C++ is just an integer constant. The pointer conversion is implicit in appropriate contexts, but this isn’t one. You need to cast explicitly:Where
Pis the appropriate type of the pointers in the collection. Alternatively, Eddie has correctly pointed out the C++11 solution which should work in modern compilers (if C++11 has been enabled).The reason that plain
NULLdoesn’t work is the following: C++ forbids implicit conversion of an integer to a pointer. There is one exception only, a literal value0is treated as a null pointer in initialisations and assignments to pointers (literal0acts as the “null pointer constant”, §4.10), andNULLis just0(§18.1.4).But when used in a template instantiation (such as in the above call to
find), C++ needs to infer a template type for each of its parameters and the type inferred for0is always the same:int. Sofindis called with anintargument (which, inside the function, is no longer a literal) and as mentioned above, there is no implicit conversion betweenintand a pointer.