c++11之all_of 、 any_of 和 none_of 的用法

0.时刻提醒自己

Note: vector的释放

1.区别

函数 功能
all_of 区间[开始, 结束)中是否所有的元素都满足判断式p,所有的元素都满足条件返回true,否则返回false。
any_of 区间[开始, 结束)中是否至少有一个元素都满足判断式p,只要有一个元素满足条件就返回true,否则返回true。
none_of 区间[开始, 结束)中是否所有的元素都不满足判断式p,所有的元素都不满足条件返回true,否则返回false。

all_of 与 none_of 是相反的,这样就不用修改判断条件了,换函数就行。

2.all_of用法

2.1 代码

// 分数
std::vector<int> vec_score{10 , 2, 33, 43, 52};

// 是否大于100
bool is_greater_than_100 = std::all_of(vec_score.begin(), vec_score.end(), [](int &item) {return 100 < item; });

if (!is_greater_than_100)
	std::cout << "不全大于100\n\n";
else
	std::cout << "全大于100\n\n";

2.2 输出结果

3.any_of用法

3.1 代码

// 分数
std::vector<int> vec_score{10 , 2, 33, 43, 52};

// 是否存在大于100的元素
bool is_exist_greater_than_100 = std::any_of(vec_score.begin(), vec_score.end(), [](int &item) {return 100 < item; });

if (is_exist_greater_than_100)
	std::cout << "存在大于100的分数\n";
else
	std::cout << "不存在大于100的分数\n\n";

3.2 输出结果

4.none_of 用法

4.1 代码

// 分数
std::vector<int> vec_score{10 , 2, 33, 43, 52};

// 检查所有分数是否全部不大于100
bool is_less_than_100 = std::none_of(vec_score.begin(), vec_score.end(), [](int &item) {return 100 < item; });

if (is_less_than_100)
	std::cout << "所有分数都不大于100\n";
else
	std::cout << "存在大于100的分数\n\n";

4.2 输出结果

5.异常

其实,上面的代码写的不够规范,因为这三个函数可能会抛出异常。 参考cppreference

拥有名为 ExecutionPolicy 的模板形参的重载按下列方式报告错误:
◦若作为算法一部分调用的函数的执行抛出异常,且 ExecutionPolicy 为标准策略之一,则调用 std::terminate 。对于任何其他 ExecutionPolicy ,行为是实现定义的。
◦若算法无法分配内存,则抛出 std::bad_alloc 。
posted @ 2020-10-21 20:30  mohist  阅读(4738)  评论(0编辑  收藏  举报