Loading... ## 概念: 返回bool类型的仿函数称为谓词 如果operator()接受一个参数,那么叫做一元谓词 如果operator()接受两个参数,那么叫做二元谓词 ## 一元谓词示例: ```cpp #include<iostream> #include<vector> using namespace std; class Greater_than_six { public: bool operator()(int than)const { return than > 6; } }; void text() { vector<int>v1; for (int i = 0; i < 10; i++) { v1.push_back(i); } vector<int>::iterator it = find_if(v1.begin(), v1.end(), Greater_than_six()); if (it == v1.end()) { cout << "没有找到符合条件的数!" << endl; } else { cout << "找到符合条件的数:" << *it << endl; } } int main() { text(); return 0; } ``` ## 二元谓词示例: ```cpp #include<iostream> #include<vector> #include<algorithm> using namespace std; class Porson { public: bool operator()(int a, int b)const { return a > b; } }; void print_two(vector<int>& v1) { for (vector<int>::iterator it = v1.begin(); it != v1.end(); it++) { cout << *it << " "; } cout << endl; } void text() { vector<int>v1; v1.push_back(10); v1.push_back(30); v1.push_back(20); v1.push_back(50); v1.push_back(40); cout << "排序前!" << endl; print_two(v1); cout << "排序后!" << endl; sort(v1.begin(), v1.end(), Porson()); print_two(v1); } int main() { text(); return 0; } ``` 最后修改:2021 年 09 月 23 日 © 允许规范转载 打赏 赞赏作者 支付宝微信 赞 如果文章有用,请随意打赏。