C++ <algorithm> std::any_of
The std::any_of function template in C++ checks if any element in a given range satisfies a specified condition. It is part of the C++ Standard Library’s <algorithm> header and is used to determine if at least one element in a sequence meets a particular criterion.
Syntax of std::any_of
template <class InputIterator, class UnaryPredicate>
bool any_of(InputIterator first, InputIterator last, UnaryPredicate pred);
Parameters of std::any_of
| Parameter | Description |
|---|---|
first | An input iterator to the initial position in a sequence. |
last | An input iterator to the final position in a sequence (one past the last element). |
pred | A unary function that accepts an element in the range as an argument and returns a value convertible to bool. The value returned indicates whether the element satisfies the condition checked by this function. The function shall not modify its argument. |
Return Value of std::any_of
Returns true if the predicate pred returns true for any of the elements in the range [first, last); otherwise, returns false. If the range is empty, the function returns false.
Exceptions for std::any_of
Throws an exception if either pred or an operation on an iterator throws an exception. Note that invalid parameters cause undefined behavior.
Examples for any_of
Example 1: Using std::any_of to Check for Negative Numbers
In this example, we use std::any_of to determine if any elements in a vector are negative numbers.
Program
#include <iostream>
#include <vector>
#include <algorithm> // For std::any_of
int main() {
std::vector<int> numbers = {1, 2, -3, 4, 5};
bool has_negative = std::any_of(numbers.begin(), numbers.end(), [](int i) {
return i < 0;
});
if (has_negative) {
std::cout << "There are negative elements in the range." << std::endl;
} else {
std::cout << "All elements are non-negative." << std::endl;
}
return 0;
}
Output
There are negative elements in the range.
Explanation
- We include the necessary headers:
<iostream>for input/output operations,<vector>for thestd::vectorcontainer, and<algorithm>for thestd::any_offunction. - We define a vector
numberscontaining the integers 1, 2, -3, 4, and 5. - We use
std::any_ofwith a lambda function to check if any elements in the vector are less than 0. - If
has_negativeistrue, we print “There are negative elements in the range.”; otherwise, we print “All elements are non-negative.”
Example 2: Using std::any_of with an Empty Range
This example demonstrates that std::any_of returns false when applied to an empty range.
Program
#include <iostream>
#include <vector>
#include <algorithm> // For std::any_of
int main() {
std::vector<int> empty_vector;
bool result = std::any_of(empty_vector.begin(), empty_vector.end(), [](int i) {
return i < 0;
});
std::cout << "Result for empty vector: " << std::boolalpha << result << std::endl;
return 0;
}
Output
Result for empty vector: false
Explanation
- We include the necessary headers:
<iostream>for input/output operations,<vector>for thestd::vectorcontainer, and<algorithm>for thestd::any_offunction. - We define an empty vector
empty_vector. - We use
std::any_ofwith a lambda function to check if any elements in the empty vector are less than 0. Since the range is empty,std::any_ofreturnsfalse. - We print the result, which is
false, indicating that no elements satisfy the condition in an empty range.
Example 3: Using std::any_of with a Custom Predicate
In this example, we define a custom predicate function to check if any elements in a list are odd numbers.
Program
#include <iostream>
#include <list>
#include <algorithm> // For std::any_of
bool is_odd(int n) {
return n % 2 != 0;
}
int main() {
std::list<int> numbers = {2, 4, 6, 8, 10};
bool has_odd = std::any_of(numbers.begin(), numbers.end(), is_odd);
if (has_odd) {
std::cout << "There are odd numbers in the list." << std::endl;
} else {
std::cout << "All numbers are even." << std::endl;
}
return 0;
}
Output
All numbers are even.
Explanation
- The program includes the necessary headers:
<iostream>for input/output operations,<list>for thestd::listcontainer, and<algorithm>for thestd::any_offunction. - A custom predicate function
is_oddis defined, which returnstrueif a number is odd andfalseotherwise. - A list
numbersis initialized with even numbers: 2, 4, 6, 8, and 10. - The
std::any_offunction is used with the custom predicate to check if any number in the list is odd. - Since all numbers are even,
has_oddisfalse, and the program outputs “All numbers are even.”
Examples to Handle Exceptions thrown by algorithm any_of Function
Example 1: Predicate Throws an Exception
This example demonstrates a case where the predicate function throws an exception during execution.
Program
#include <iostream>
#include <vector>
#include <algorithm>
#include <stdexcept>
bool faulty_predicate(int n) {
if (n < 0) {
throw std::runtime_error("Negative number encountered.");
}
return n % 2 == 0;
}
int main() {
std::vector numbers = {-2, 4, -6, 8, 10};
try {
bool result = std::any_of(numbers.begin(), numbers.end(), faulty_predicate);
std::cout << "At least one element is even: " << std::boolalpha << result << std::endl;
} catch (const std::runtime_error& e) {
std::cout << "Exception caught: " << e.what() << std::endl;
}
return 0;
}
Output
Exception caught: Negative number encountered.
Explanation
- The program defines a predicate function
faulty_predicatethat throws astd::runtime_errorif a negative number is encountered. - A vector
numbersis initialized, including a negative number. - The
std::any_offunction applies the predicate to each element of the vector. When it encounters the negative number, the predicate throws an exception. - The exception is caught in the try-catch block, and an error message is printed.
Example 2: Iterator Throws an Exception
This example demonstrates a case where a custom iterator throws an exception during iteration.
Program
#include <iostream>
#include <vector>
#include <algorithm>
#include <stdexcept>
class FaultyIterator {
public:
using iterator_category = std::input_iterator_tag;
using value_type = int;
using difference_type = std::ptrdiff_t;
using pointer = const int*;
using reference = const int&;
FaultyIterator(const int* ptr, bool fail_after = false)
: ptr(ptr), fail_after(fail_after), count(0) {}
reference operator*() const {
if (fail_after && count >= 0) {
throw std::runtime_error("Iterator error.");
}
return *ptr;
}
FaultyIterator& operator++() {
++ptr;
++count;
return *this;
}
bool operator!=(const FaultyIterator& other) const {
return ptr != other.ptr;
}
bool operator==(const FaultyIterator& other) const {
return ptr == other.ptr;
}
private:
const int* ptr;
bool fail_after;
int count;
};
int main() {
int arr[] = {1, 2, 3};
try {
bool result = std::any_of(
FaultyIterator(arr, true),
FaultyIterator(arr + 3),
[](int n) { return n > 0; });
std::cout << "At least one positive element: " << std::boolalpha << result << std::endl;
} catch (const std::runtime_error& e) {
std::cout << "Exception caught: " << e.what() << std::endl;
}
return 0;
}
Output
Exception caught: Iterator error.
Explanation
- The program defines a custom iterator
FaultyIteratorthat throws astd::runtime_errorafter accessing two elements. - An array
arris initialized with three elements. - The
std::any_offunction applies a lambda predicate to the elements. The iterator throws an exception during iteration. - The exception is caught in the
try-catchblock, and an error message is printed.
