NULL search in vector

I would like to know if the pointer vector contains a NULL record, preferably using code in STL and not writing a loop. I tried this expression:

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

But I get errors telling me that I have a "comparison between pointer and integer". Is there a better way to do this?

+6
source share
3 answers

NULL in C ++ is an integer constant. Pointer conversion is implied in appropriate contexts, but it is not one. You need to explicitly specify:

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

Where P is the corresponding type of pointers in the collection. As an alternative, Eddie correctly identified a C ++ 11 solution that should work in modern compilers (if C ++ 11 is enabled).


The reason plain NULL does not work is as follows: C ++ prohibits the implicit conversion of an integer to a pointer. Only one exception, the literal value 0 treated as a null pointer in initialization and assignment to pointers (the literal 0 acts as a β€œnull pointer constant”, Β§4.10), and NULL is just 0 (Β§18.1.4).

But when used in creating an instance of a template (for example, in the find call above), C ++ should infer the type of the template for each of its parameters, and the type output for 0 is always the same: int . Therefore, 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 the int and the pointer.

+12
source

Try

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

It is assumed that you are using the new C ++ 11 standard.

As I said in the comment above, NULL is actually #define NULL 0, more accurate is an integer.

If you are not using C ++ 11, try:

 std::find(dependent_events.begin(), dependent_events.end(), static_cast<void*>(NULL)); 
+10
source

Just draw NULL as a pointer. In C ++, NULL is an integer constant.

 std::find(dependent_events.begin(), dependent_events.end(), (int *)NULL); 

Obviously substitute any type of data that the vector holds for int *

+2
source

Source: https://habr.com/ru/post/896912/


All Articles