看本篇内容前,请先掌握C++ lambda函数的内容:
头文件:
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