本节我们开始谓词判断算法的学习。那什么是谓词判断算法呢?首先我们要知道什么是查询算法,它指的是一类只能进行查询而不能修改元素的算法,其中,谓词判断算法是查询算法的一个子集,它们的功能是判断一个区间是否满足一元谓词的要求,满足则返回true,不满足则返回false。比如我们有一个序列{1,2,3,5,7,9},该序列很多元素都是奇数,我们想要知道这个序列是不是完全奇数序列,此时我们使用all_of()函数就能够对其进行高效判断,由于”2“的存在函数会返回false,我们也就知道这个序列不是完全奇数序列。主要的三个谓词判断算法是:all_of()函数、any_of()函数、none_of()函数,它们的函数语法格式如下:
// 三个函数具有相同的参数列表 template< class InputIt, class UnaryPredicate > bool all_of( InputIt first, InputIt last, UnaryPredicate p ); template< class InputIt, class UnaryPredicate > bool any_of( InputIt first, InputIt last, UnaryPredicate p ); template< class InputIt, class UnaryPredicate > bool none_of( InputIt first, InputIt last, UnaryPredicate p );
其中,all_of(first,last,pred)函数的功能是在指定区间[first,last)内进行一元谓词判断,只有所有元素满足一元谓词条件才会返回true,否则返回false;
any_of(first, last, pred) 函数的功能是在指定区间 [first, last) 内进行一元谓词判断,只要至少有一个元素满足一元谓词条件就会返回 true,只有当所有元素都不满足条件时才返回 false;
none_of(first, last, pred) 函数的功能是在指定区间 [first, last) 内进行一元谓词判断,只有当所有元素都不满足一元谓词条件时才返回 true,只要有一个元素满足条件就返回 false。
下面我们通过代码来实际操作这三个谓词判断算法:
#include<iostream>
#include<vector>
#include<functional>
#include<algorithm>
using namespace std;
// 判断是否为奇数的谓词
bool is_odd(const int& n) {
return n % 2 != 0;
}
struct IsOdd {
bool operator()(const int& n) const {
return n % 2 != 0;
}
};
// 判断是否为偶数的谓词
bool is_even(const int& n) {
return n % 2 == 0;
}
struct IsEven {
bool operator()(const int& n) const {
return n % 2 == 0;
}
};
void test1() {
vector<int> v{1, 3, 5, 7, 9}; // 改为全奇数
cout << "原序列为:";
for(auto it = v.begin(); it != v.end(); ++it) cout << *it << " ";
cout << '\n';
if(all_of(v.begin(), v.end(), is_odd))
cout << "通过all_of()函数判断该序列确实为完全奇数序列!\n";
else
cout << "该序列不是完全奇数序列!\n";
}
void test2() {
vector<int> v{1, 2, 3, 5, 7};
cout << "原序列为:";
for(auto it = v.begin(); it != v.end(); ++it) cout << *it << " ";
cout << '\n';
if(any_of(v.begin(), v.end(), is_even)) // 检查是否存在偶数
cout << "通过any_of()函数判断该序列确实存在偶数元素!\n";
else
cout << "该序列不存在偶数元素!\n";
}
void test3() {
vector<int> v{1, 3, 5, 7, 9};
cout << "原序列为:";
for(auto it = v.begin(); it != v.end(); ++it) cout << *it << " ";
cout << '\n';
if(none_of(v.begin(), v.end(), is_even)) // 检查是否没有偶数
cout << "通过none_of()函数判断该序列完全不存在偶数元素!\n";
else
cout << "该序列存在偶数元素!\n";
}
int main(){
system("title dotcpp.com");
test1();
test2();
test3();
return 0;
}编译结果如下:

对于序列{1, 3, 5, 7, 9},我们通过all_of()函数判断该序列是否完全是奇数序列,函数返回true得到输出;
对于序列{1, 2, 3, 5, 7},我们通过any_of()函数判断该序列是否存在偶数元素,函数返回true得到输出;
对于序列{1, 3, 5, 7, 9},我们通过none_of()函数判断该序列是否完全不存在偶数元素,函数返回true得到输出;
总结:本节我们总共学习了三个一元谓词判断算法,它们分别是:all_of()函数、any_of()函数、none_of()函数,重点是理解它们的函数功能,all_of()函数为”全称判断“,any_of()函数为”存在判断“,none_of()函数为”全否判断“,读者切勿混淆它们之间的概念。
C语言网提供由在职研发工程师或ACM蓝桥杯竞赛优秀选手录制的视频教程,并配有习题和答疑,点击了解:
一点编程也不会写的:零基础C语言学练课程
解决困扰你多年的C语言疑难杂症特性的C语言进阶课程
从零到写出一个爬虫的Python编程课程
只会语法写不出代码?手把手带你写100个编程真题的编程百练课程
信息学奥赛或C++选手的 必学C++课程
蓝桥杯ACM、信息学奥赛的必学课程:算法竞赛课入门课程
手把手讲解近五年真题的蓝桥杯辅导课程