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

标签 c++ c++11 stl language-lawyer

给定以下代码,

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/

相关文章:

c++ - 如何在 C++ 中创建字符数组数组? (仅使用 iostream)

c++ - volatile 成员变量

c++ - 我的 vector 获得了一个额外的索引,即使我不希望它这样做

c++ - 使用非默认比较谓词的集合容器

c++ - 将stringstream内容写入ofstream

c++ - 编译qemu-xen时signal.c出错

c++ - QTextCodec::availableCodecs 返回编解码器重复项

c++ - std::equal_range 提示 "sequence not ordered"

c++ - 在 C++ 中获取环境变量 - 我得到 NULL

c++ - 如果本地 std::function 超出其 "life"有什么问题吗?