Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is std::any_of required to follow short circuit logic?

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?

like image 514
Klemen Forstnerič Avatar asked Dec 07 '17 09:12

Klemen Forstnerič


1 Answers

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.

like image 131
StoryTeller - Unslander Monica Avatar answered Nov 18 '22 23:11

StoryTeller - Unslander Monica