C++ //谓词 //一元谓词 //概念:返回bool类型的仿函数称为 谓词 //如果 operator()接受一个参数,那么叫做一元谓词 //如果 operator()接受 2 个参数,那么叫做一元谓词
1 //谓词 2 //一元谓词 3 //概念:返回bool类型的仿函数称为 谓词 4 //如果 operator()接受一个参数,那么叫做一元谓词 5 //如果 operator()接受 2 个参数,那么叫做一元谓词 6 7 #include<iostream> 8 #include<string> 9 #include<vector> 10 #include<algorithm> 11 #include<list> 12 #include<map> 13 #include<set> 14 #include<deque> 15 16 using namespace std; 17 //一元谓词 18 class GreaterFive 19 { 20 public: 21 bool operator()(int val) 22 { 23 return val > 5; 24 } 25 }; 26 27 void test01() 28 { 29 vector<int>v; 30 for (int i = 0; i < 10; i++) 31 { 32 v.push_back(i); 33 } 34 //查找容器中有没有大于 5 的数字 35 // GreaterFive() 匿名的函数对象 36 vector<int>::iterator it= find_if(v.begin(), v.end(), GreaterFive()); 37 if (it == v.end()) 38 { 39 cout << "未找到!" << endl; 40 } 41 else 42 { 43 cout << "找到了大于5的数字为:" << *it << endl; 44 } 45 46 47 48 } 49 class MyCompare 50 { 51 public: 52 bool operator()(int val, int va2) 53 { 54 return val > va2; 55 } 56 }; 57 58 59 //二元谓词 60 void test02() 61 { 62 vector<int>v; 63 v.push_back(10); 64 v.push_back(20); 65 v.push_back(90); 66 v.push_back(80); 67 v.push_back(50); 68 69 sort(v.begin(), v.end()); 70 for (vector<int>::iterator it = v.begin(); it != v.end(); it++) 71 { 72 cout << *it << " "; 73 } 74 cout << endl; 75 //使用函数对象 改变算法策略 改变排序规则 76 sort(v.begin(), v.end(),MyCompare()); 77 78 cout << "------------------------" << endl; 79 for (vector<int>::iterator it = v.begin(); it != v.end(); it++) 80 { 81 cout << *it << " "; 82 } 83 cout << endl; 84 85 //list<int>l; 86 //l.push_back(10); 87 //l.sort(); 88 89 //set<int>s; 90 //s.insert(20); 91 // 92 93 //map<int, int>m; 94 //m.insert(make_pair(1, 20)); 95 //m.insert(pair<int, int>(10, 20)); 96 //m[3] = 50; 97 // 98 //deque<int>d; 99 //d.push_back(20); 100 //d.push_front(20); 101 //sort(d.begin(), d.end()); 102 } 103 104 int main() 105 { 106 test01(); 107 test02(); 108 }
本文来自博客园,作者:Bytezero!,转载请注明原文链接:https://www.cnblogs.com/Bytezero/p/15149424.html