C++ 学习之内建函数对象 - 关系仿函数和逻辑仿函数

关系仿函数原型:

  • 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;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值