1. 一元谓词
#include <iostream>
#include<vector>
#include<algorithm>using namespace std;class CreaterFive{
public:bool operator()(int val){return val>5;}
};int main()
{vector<int> vec;for(int i=0; i<=10; ++i){vec.push_back(i);}vector<int>::iterator it = find_if(vec.begin(), vec.end(), CreaterFive());if(it==vec.end()){cout << "未找到" << endl;}else{cout << "找到,为:"<< *it << endl;}return 0;
}
输出:
2. 二元谓词
#include <iostream>
#include<vector>
#include<algorithm>using namespace std;class MyCompare{
public:bool operator()(int a, int b){return a > b;}
};int main()
{vector<int> vec;vec.push_back(10);vec.push_back(30);vec.push_back(50);vec.push_back(100);vec.push_back(60);sort(vec.begin(), vec.end(), MyCompare()); //利用二元谓词修改排序方式for(vector<int>::iterator it=vec.begin(); it<vec.end(); it++){cout << *it <<" ";}cout << endl; return 0;
}