DEV Community

loading...
Cover image for all_of, any_of, none_of: Examine a range of elements for a particular condition in C++

all_of, any_of, none_of: Examine a range of elements for a particular condition in C++

Satyam Lachhwani
Exploring ways to find out what's good for me... Interested in web.
・2 min read

C++ has a rich set of utilities that most people are not completely aware of. It also has these useful functions which examine whether or not a range of elements satisfy a particular condition.

Let's see them in action before going further:

vector<int> arr(10);
iota(arr.begin(), arr.begin() + 10, 1);
// arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

// Checks if all elements are equal to 2 (returns false)
cout<<all_of(arr.begin(), arr.end(), [](int i){return i == 2;});

// Checks if any element is even (returns true)
cout<<any_of(arr.begin(), arr.end(), [](int i){return (i&1) == 0;});

// Checks if no element is divisible by 13 (returns true)
cout<<none_of(arr.begin(), arr.end(), [](int i){return i%13 == 0;});

Enter fullscreen mode Exit fullscreen mode

PS: If you're not familiar with the function syntax, please read this.

To achieve the same thing, we can always iterate through all the elements and check but I think these functions are still useful as they make the task even easier. 😉

Let's now move forward and know more about these functions.
 

Use

Include the required header file in order to be able to use any_of, all_of, none_of functions. You can either include bits/stdc++.h or include algorithm on the top of your .cpp file.
 

Accepted function parameters

  1. Starting address of the container
  2. Ending address (range up to which the elements would be examined)
  3. Unary predicate (basically a function that would return a boolean value)  

Return value

📍 all_of returns true if the unary predicate returns true for all the elements in the given range.

📍 any_of returns true if the unary predicate returns true for at least one of the elements in the given range.

📍 none_of returns true if the unary predicate returns true for no element in the given range.
 

For full reference, visit here

If you find anything wrong or if you know some more exciting functions or other stuff related to C++, please drop a comment below so we learn together.

My Profile -

Github
LinkedIn

Discussion (0)