gpt4 book ai didi

c++ - any_of 与 find_if

转载 作者:IT老高 更新时间:2023-10-28 21:41:28 29 4
gpt4 key购买 nike

C++11 介绍 any_ofalgorithm秒。

这似乎与 find_if 完全一样.

假设我有一个仿函数:function<bool(int)> foo;还有一个数组:vector<int> bar;

这两个调用似乎做了完全相同的事情:

any_of(bar.begin(), bar.end(), foo);

bar.end() != find_if(bar.begin(), bar.end(), foo);

我进一步觉得all_of , 和 none_of可以通过否定 find_if 来完成声明。

这些算法是否只是为了与 end 进行比较?对我们来说,还是有我不明白的用处?

最佳答案

我相信你是对的,它们只是更方便的接口(interface),可以通过其他方式实现。

将它们添加到标准中的建议 (N2666) 说:

These three algorithms provide the ordinary mathematical operations ∀, ∃, and ∄: given a range and a predicate, determine whether that predicate is true for all elements; whether there exists an element for which the predicate is true; or whether there exist no elements for which the predicate is true. Strictly speaking there is no need to provide all three of these algorithms (!none_of and any_of are equivalent), but all three of these operations feel equally fundamental.

与包含 find_if 和(不)相等的表达式相比,这些名称更自然且更易于阅读(当然对于非专业 C++ 程序员而言)。

GCC 的标准库通过简单地调用其他函数来实现它们:

all_of(first, last, pred)return last == std::find_if_not(first, last, pred);

none_of(first, last, pred)return last == std::find_if(first, last, pred);

any_of(first, last, pred)return !none_of(first, last, pred);

关于c++ - any_of 与 find_if,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27425999/

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