谓词
谓词概念
一元谓词
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
class GreaterFive{
public:
bool operator()(int val){
return val > 5;
}
};
void test() {
vector<int> v;
for (int i = 0; i < 10; ++i) {
v.push_back(i);
}
vector<int> ::iterator it = find_if(v.begin(),v.end(),GreaterFive());
if(it == v.end()){
cout << "没有大于5的数" << endl;
} else{
cout << "大于5的数是:" << *it << endl;
}
}
int main() {
test();
return 0;
}
二元谓词
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
class MyCompare {
public:
bool operator()(int v1, int v2) {
return v1 > v2;
}
};
void test() {
vector<int> v;
v.push_back(10);
v.push_back(90);
v.push_back(70);
v.push_back(30);
v.push_back(20);
v.push_back(70);
sort(v.begin(), v.end());
for (vector<int>::iterator it = v.begin(); it != v.end(); it++) {
cout << *it << " ";
}
cout << endl;
sort(v.begin(), v.end(),MyCompare());
for (vector<int>::iterator it = v.begin(); it != v.end(); it++) {
cout << *it << " ";
}
cout << endl;
}
int main() {
test();
return 0;
}