给定以下代码,
std::vector<int> numbers = {1, 2, 3, 4, 5};
std::any_of(std::begin(numbers), std::end(numbers),
[](int number) { return number > 3; } );
std::any_of 是否需要(按标准)在达到 4 时立即返回?
最佳答案
标准本身并没有提出任何这样的硬性要求。但是可以推断它是间接鼓励的([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.
虽然一个完全符合的实现可能会应用谓词 exactly last-first
次,但对我来说,这种措辞听起来像是鼓励尽快退出。
请注意,几乎不可能询问接受 ExecutionPolicy
的重载。从那时起,评估的顺序就不得而知了。
在不太正式的说明中,任何不在谓词为真时退出的顺序版本的实现都会对其作者的凭据产生质疑。
关于c++ - 是否需要 std::any_of 遵循短路逻辑?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47692180/