C++的all_of、any_of、none_of

看本篇内容前,请先掌握C++ lambda函数的内容:

C++ lambda_巨龙之路的博客-CSDN博客

头文件:

algorithm

all_of、any_of、none_of的函数原型:

bool all_of (InputIterator first, InputIterator last, UnaryPredicate pred);

bool any_of (InputIterator first, InputIterator last, UnaryPredicate pred);

bool none_of (InputIterator first, InputIterator last, UnaryPredicate pred);

first:列表中的第一个元素。

last:列表中的最后一个元素。

pred:判断函数,一般为lambda函数

举个例子

#include<iostream>
#include<algorithm>

int main(){
	int scores[10]={76,59,45,98,88,33,99,100,22,65};
	if(std::none_of(scores,scores+10,[=](int k) {return k<60;})){
		std::cout<<"没有学生不及格";	
	}
	else{
		std::cout<<"有学生不及格";	
	}
}

 

all_of、none_of、any_of的列表参数可以是数组、也可以是容器:

举个例子

#include<iostream>
#include<algorithm>
#include<vector>

int main(){
	int scores[10]={76,59,45,98,88,33,99,100,22,65};
	if(std::none_of(scores,scores+10,[=](int k) {return k<60;})){
		std::cout<<"没有学生不及格"<<std::endl;	
	}
	else{
		std::cout<<"有学生不及格"<<std::endl;	
	}
	
	std::vector<int> student_height={167,172,181,165,175,176};
	if(std::any_of(student_height.begin(),student_height.end(),
		[=](int x){return x>180;}))
	{
			std::cout<<"有学生身高超过180"<<std::endl;	
	}
	else{
		std::cout<<"没有学生身高超过180"<<std::endl;	
	}	
		
}

 

all_of、none_of、any_of返回true的条件:

all_of:判断函数全都返回true时,all_of才返回true

none_of:判断函数全都返回false时,none_of才返回true

any_of:判断函数只要有一个返回true,any_of就返回true

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

巨龙之路

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值