Engineer bro!

Fri Nov 12 2021 (8 months ago)

Engineer by mistake!

I am a software engineer by passion

The all_any_none_of function in c++ | STL

In this article, we'll see how to use `all_of`, `any_of` and `none_of` function in c++.

You must include the header `bits/stdc++.h`

all_of

`all_of` the function returns true if all of the elements of the given input array/vector passes the test.

For example, you want to check if the array contains all even numbers or not. For that, you can use the function like below.

Code

``````int main() {
vector<int> v{4, 6, 8, 10};

if (all_of(v.begin(), v.end(), [](int num) { return num % 2 == 0; })) {
cout << "All numbers are even";
} else {
cout << "All numbers are not even";
}
return 0;
}
``````

output

``````All numbers are even
``````

The third argument is a lambda function, which will check if the current element is even or odd.

Code

``````int main() {
vector<int> v{4, 6, 8, 10,15};

if (all_of(v.begin(), v.end(), [](int num) { return num % 2 == 0; })) {
cout << "All numbers are even";
} else {
cout << "All numbers are not even";
}
return 0;
}
``````

output

``````All numbers are not even
``````

any_of

`any_of` function is used to check if any of the elements of the array passes the test or not.

Code

``````int main() {
vector<int> v{1,5,8,7};

if (any_of(v.begin(), v.end(), [](int num) { return num % 2 == 0; })) {
cout << "A number of the array is even";
} else {
cout << "There is no even numbers in the array";
}
return 0;
}
``````

Output

``````A number of the array is even
``````

Code

``````int main() {
vector<int> v{1,5,81,7};

if (any_of(v.begin(), v.end(), [](int num) { return num % 2 == 0; })) {
cout << "A number of the array is even";
} else {
cout << "There is no even numbers in the array";
}
return 0;
}
``````

Output

``````There is no even numbers in the array
``````

none_of

`none_of` the function returns true if none of the elements passes the test.

Code

``````int main() {
vector<int> v{4, 61, 8};

if (none_of(v.begin(), v.end(), [](int num) { return num % 2 == 0; })) {
cout << "None of the numbers is even";
} else {
cout << "There are some even numbers";
}
return 0;
}
``````

O/P

``````There are some even numbers
``````

Code

``````int main() {
vector<int> v{41, 61, 81};

if (none_of(v.begin(), v.end(), [](int num) { return num % 2 == 0; })) {
cout << "None of the numbers is even";
} else {
cout << "There are some even numbers";
}
return 0;
}
``````

O/P

``````None of the numbers is even
``````

C++