Given the following code,
std::vector<int> numbers = {1, 2, 3, 4, 5};
std::any_of(std::begin(numbers), std::end(numbers),
[](int number) { return number > 3; } );
is std::any_of required (by the standard) to return as soon as it reaches 4?
The standard itself doesn't place any such hard requirement. But one may infer it is indirectly encouraged ([alg.any_of]):
template <class InputIterator, class Predicate> bool any_of(InputIterator first, InputIterator last, Predicate pred); template <class ExecutionPolicy, class ForwardIterator, class Predicate> bool any_of(ExecutionPolicy&& exec, ForwardIterator first, ForwardIterator last, Predicate pred);
Returns: false if [first, last) is empty or if there is no iterator i in the range [first, last) such that pred(*i) is true, and true otherwise.
Complexity: At most last - first applications of the predicate.
While a perfectly conforming implementation may apply the predicate exactly last-first
times, the wording to me sounds like it would be encouraged to exit as soon as possible.
Note that it's virtually impossible to ask the same of the overload that accepts an ExecutionPolicy
. Since then the order of evaluation is not known.
On a less formal note, any implementation of the sequential version that does not exit the moment the predicate is true, puts the credentials of its author into question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With