关系仿函数原型:
template<class T> bool greater<T>
//大于template<class T> bool greater_equal<T>
//大于等于template<class T> bool equal_to<T>
//等于template<class T> bool not_equal_to<T>
//不等于template<class T> bool less<T>
//小于template<class T> bool less_equal<T>
//小于等于
逻辑仿函数原型:
template<class T> bool logical_and<T>
//逻辑与template<class T> bool logical_or<T>
//逻辑或template<class T> bool logical_not<T>
//逻辑非
#include<iostream>
#include<algorithm>
#include<vector>
#include<functional>//包含内建函数对象的头文件
using namespace std;
/***************************************关系仿函数***********************************/
/*bool myCompare(int v1, int v2)//自己写一个普通函数也可以指定排序规则
{
return v1 > v2;
}*/
//返回bool类型的仿函数称为谓词
class myCompare//自己写一个谓词也可以
{
public:
bool operator()(int v1,int v2)
{
return v1 > v2;
}
};
void test01()//改变排序规则:降序
{
vector<int> v;
v.push_back(5);
v.push_back(10);
v.push_back(1);
v.push_back(20);
for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
{
cout << *it <<" ";
}
cout << endl;
//sort(v.begin(), v.end(), myCompare);//自己写一个普通函数也可以
//sort(v.begin(), v.end(), myCompare());//自己写一个仿函数也可以
sort(v.begin(), v.end(), greater<int>());//用系统提供的关系仿函数也可以
for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
{
cout << *it <<" ";
}
cout << endl;
}
/***************************************逻辑仿函数***********************************/
void test02()//将一个容器中的数据拷贝到另一个容器中
{
vector<bool> v;//存放bool类型的数组
v.push_back(true);
v.push_back(true);
v.push_back(true);
v.push_back(true);
for (vector<bool>::iterator it = v.begin(); it != v.end(); it++)
{
cout << *it << " ";//输出 1 1 1 1
}
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 << " ";//输出 0 0 0 0
}
}
int main()
{
//test01();//关系仿函数
test02(); //逻辑仿函数
return 0;
}