Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding NULL in a vector

Tags:

c++

stl

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?

like image 667
Nels Beckman Avatar asked Sep 08 '11 19:09

Nels Beckman


2 Answers

NULL in C++ is just an integer constant. The pointer conversion is implicit in appropriate contexts, but this isn’t one. You need to cast explicitly:

std::find(dependent_events.begin(), dependent_events.end(), static_cast<P>(0));

Where P is 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 NULL doesn’t work is the following: C++ forbids implicit conversion of an integer to a pointer. There is one exception only, a literal value 0 is treated as a null pointer in initialisations and assignments to pointers (literal 0 acts as the “null pointer constant”, §4.10), and NULL is just 0 (§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 for 0 is always the same: int. So find is called with an int argument (which, inside the function, is no longer a literal) and as mentioned above, there is no implicit conversion between int and a pointer.

like image 58
Konrad Rudolph Avatar answered Oct 03 '22 22:10

Konrad Rudolph


Try

std::find(dependent_events.begin(), dependent_events.end(), nullptr)

This is assuming you are using the new c++11 standard.

Like I said in the comment above, NULL is actually a #define NULL 0, an integer to be more precise.

If not using c++11, try:

std::find(dependent_events.begin(), dependent_events.end(), static_cast<void*>(NULL));
like image 26
EddieBytes Avatar answered Oct 03 '22 23:10

EddieBytes