目录
1.函数对象使用
2.谓词
1.一元谓词
2.二元谓词
3.内建函数对象
1.算术仿函数
2.关系仿函数
3.逻辑仿函数
1.函数对象使用
#include<bits/stdc++.h>
using namespace std;class add
{
public:int operator()(int v1,int v2){return v1 + v2;}
};class print
{
public:void operator()(string s){cout << s << endl;}
};int main()
{add a;cout << a(5,6) << endl;print p;p("hello!!!!!");return 0;
}
2.谓词
1.一元谓词
#include<bits/stdc++.h>
using namespace std;class dayu5
{
public:bool operator()(int v){return v > 5;}
};int main()
{vector<int> v;v.push_back(7);v.push_back(9);v.push_back(5);v.push_back(100);v.push_back(3);//查找容器内有没有大于5的数//dayu5是匿名函数对象vector<int>::iterator it = find_if(v.begin(),v.end(),dayu5());//找到了返回迭代器位置,没找到时返回的是尾迭代器if(it != v.end()) cout << "找到了,开心。" << *it << endl; return 0;
}
2.二元谓词
#include<bits/stdc++.h>
using namespace std;class cmp
{
public:bool operator()(int v1,int v2){return v1 > v2;}
};int main()
{vector<int> v;v.push_back(7);v.push_back(9);v.push_back(5);v.push_back(100);v.push_back(3);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(),cmp());cout << "------------------" << endl;for(vector<int>::iterator it = v.begin(); it != v.end(); it++){cout << *it << ' ';}return 0;
}
3.内建函数对象
1.算术仿函数
#include<bits/stdc++.h>
using namespace std;int main()
{//取反仿函数negate<int> n;cout << n(50) << endl;//对50取反plus<int> p;//加法仿函数,传int类型的数进去相加cout << p(33,23) << endl;return 0;
}
2.关系仿函数
#include<bits/stdc++.h>
using namespace std;int main()
{vector<int> v;v.push_back(7);v.push_back(9);v.push_back(5);v.push_back(100);v.push_back(3);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(),greater<int>());cout << "------------------" << endl;for(vector<int>::iterator it = v.begin(); it != v.end(); it++){cout << *it << ' ';}return 0;
}
3.逻辑仿函数
#include<bits/stdc++.h>
using namespace std;int main()
{vector<bool> v;v.push_back(1);v.push_back(1);v.push_back(0);v.push_back(0);v.push_back(1);for(vector<bool>::iterator it = v.begin(); it != v.end(); it++){cout << *it << ' ';}cout << endl;//将容器v搬到容器v1并且用logical_not进行取反的操作vector<bool> v1;v1.resize(v.size());transform(v.begin(),v.end(),v1.begin(),logical_not<bool>());for(vector<bool>::iterator it = v1.begin(); it != v1.end(); it++){cout << *it << ' ';}cout << endl;return 0;
}