C++ //内建函数对象 算数仿函数 关系仿函数 //逻辑仿函数
1 //内建函数对象 算数仿函数 关系仿函数 //逻辑仿函数 2 #include<iostream> 3 #include<string> 4 #include<functional> //内建函数对象头文件 5 #include<vector> 6 #include<algorithm> 7 8 //using namespace std; 9 using namespace std; 10 11 //negate 一元仿函数 取反仿函数 12 void test01() 13 { 14 negate<int>n; 15 16 cout<<n(50)<<endl; 17 } 18 19 20 21 22 //plus 二元仿函数 加法 23 void test02() 24 { 25 plus<int>p; 26 27 cout << p(10,20) << endl; 28 } 29 30 //关系仿函数 31 class MyCompare 32 { 33 public: 34 bool operator()(int v1,int v2)//const 35 { 36 return v1 > v2; 37 } 38 }; 39 40 41 //大于 greater 42 void test03() 43 { 44 vector<int>v; 45 v.push_back(10); 46 v.push_back(60); 47 v.push_back(80); 48 v.push_back(30); 49 v.push_back(20); 50 51 for (vector<int>::iterator it = v.begin(); it != v.end(); it++) 52 { 53 cout << *it << " "; 54 } 55 cout << endl; 56 57 //升序 58 59 sort(v.begin(), v.end()); 60 cout << "升序" << endl; 61 for (vector<int>::iterator it = v.begin(); it != v.end(); it++) 62 { 63 cout << *it << " "; 64 } 65 cout << endl; 66 67 //降序 68 // greater<int>() 内建函数 69 //sort(v.begin(), v.end(), MyCompare()); 70 sort(v.begin(), v.end(), greater<int>()); 71 cout << "降序" << endl; 72 for (vector<int>::iterator it = v.begin(); it != v.end(); it++) 73 { 74 cout << *it << " "; 75 } 76 cout << endl; 77 78 79 80 81 } 82 83 //逻辑仿函数 84 //逻辑非 longical_not 85 void test04() 86 { 87 vector<bool>v; 88 v.push_back(true); 89 v.push_back(false); 90 v.push_back(true); 91 v.push_back(false); 92 93 cout << "v容器 =" << endl; 94 for (vector<bool>::iterator it = v.begin(); it != v.end(); it++) 95 { 96 cout << *it << " "; 97 } 98 cout << endl; 99 100 //利用逻辑非 将容器v 搬运到 容器 V2中,并执行取反操作 101 102 vector<bool>v2; 103 v2.resize(v.size()); 104 105 transform(v.begin(),v.end(),v2.begin(),logical_not<bool>()); 106 107 cout << "v2容器 =" << endl; 108 for (vector<bool>::iterator it = v2.begin(); it != v2.end(); it++) 109 { 110 111 cout<<* it << " "; 112 } 113 cout << endl; 114 115 116 117 } 118 119 120 121 int main() 122 { 123 124 test01(); 125 test02(); 126 test03(); 127 test04(); 128 129 130 system("pause"); 131 return 0; 132 }
本文来自博客园,作者:Bytezero!,转载请注明原文链接:https://www.cnblogs.com/Bytezero/p/15151009.html