c++rangeanyof

std::ranges::any_of Order implementation details


I am looking at cppreference but I don't see any information on the order of the executed loop.

My question: when calling std::ranges::any_of on data.begin(), data.end() am I sure it goes from begin() to end() in order and it stop once true?


Solution

  • am I sure it goes from begin() to end() in order and it stop once true?

    No, there is no such guarantee.

    According to the stated complexity for std::ranges::any_of:

    At most last - first applications of the predicate and the projection.

    The implementation is free to iterate in a different order than the one you mentioned (e.g. in reverse order). It is also not obligated to stop at the first elements for which the predicate is true. The only guarantee is that it will use the predicate/projection on each element at most 1 time.

    Having said that, what you mentioned is a very reasonable expectation from any "normal" implementation, and I assume all of them will follow it (although as I said it is not mandated).