gpt4 book ai didi

c++ - 是否需要 std::any_of 遵循短路逻辑?

转载 作者:IT老高 更新时间:2023-10-28 12:45:49 26 4
gpt4 key购买 nike

给定以下代码,

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com