This tutorial will discuss about a unique way to check if any element in array is null in C++.
To check an array has any NULL value, we will use the std::any_of()
function from STL Algorithms.
The std::any_of()
function accepts three arguments,
- Iterator pointing to the start of a sequence.
- Iterator pointing to the end of a sequence.
- A Callback or Lambda function which accepts a value of same type as the type of sequence, and returns a boolean value.
The std::any_of()
function will apply the given Lambda function on all the elements of the sequence and it returns true if the callback function returns true for any element of sequence.
So, to check if an array of pointers contains a NULL value, we can use the std::any_of()
function. i.e.
int* arr[] = {new int(5), nullptr, new int(7), nullptr, new int(3)}; // Check if there is any NULL value in the array bool result = std::any_of( std::begin(arr), std::end(arr), [](const int* ptr) { return ptr == nullptr; });
We passed three arguments in the std::any_of() function,
- Iterator pointing to the start of array i.e. iterator returned by
std::begin(arr)
. - Iterator pointing to the end of array i.e. iterator returned by
std::end(arr)
. - A Lambda function which accepts an pointer as an argument, and returns
true
if the given pointer is NULL.
The any_of()
function will return true, if there is any NULL Pointer in the array.
Frequently Asked:
- Check if Any Element of Array is in Another Array in C++
- How to Sort an Array of pairs in C++?
- Create an Array of pointers in C++
- Check if All elements of Array are equal in C++
Let’s see the complete example,
#include <iostream> #include <algorithm> int main() { int* arr[] = {new int(5), nullptr, new int(7), nullptr, new int(3)}; // Check if there is any NULL value in the array bool result = std::any_of( std::begin(arr), std::end(arr), [](const int* ptr) { return ptr == nullptr; }); if (result) { std::cout << "Yes, Array has at least one NULL value " << std::endl; } else { std::cout << "No, Array does not have any NULL value " << std::endl; } // Free the memory allocated with new in array for (const int* ptr: arr) { delete ptr; } return 0; }
Output :
Yes, Array has at least one NULL value
Summary
Today we learned about several ways to check if any element in array is null in C++. Thanks.