DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป

DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป is a community of 966,904 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for all_of, any_of, none_of: Examine a range of elements for a particular condition in C++
Satyam Lachhwani
Satyam Lachhwani

Posted on

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

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

Top comments (0)

๐ŸŒš Friends don't let friends browse without dark mode.

Sorry, it's true.