内建函数对象

即STL内部建立的一些函数对象

分类:

  • 算术仿函数
  • 关系仿函数
  • 逻辑仿函数

用法:

  • 这些仿函数所使用产生的对象,用法和一般函数完全相同
  • 使用内建函数对象,需要引入头文件#include<functional> 

 算术仿函数

功能描述:

  • 实现四则运算
  • 其中negate是一元运算

仿函数原型:

  • template<class T> T plus<T>     //加法仿函数
  • template<class T> T minus<T>     //减法仿函数
  • template<class T> T multiplies<T>     //乘法仿函数
  • template<class T> T divides<T>     //除法仿函数
  • template<class T> T modulus<T>     //取模仿函数
  • template<class T> T negate<T>     //取反仿函数

#include<iostream>
#include<vector>
#include<functional>
//#include<stdio.h>
using namespace std;

int main()
{
	negate<int>n;
	cout<<n(50)<<endl;
	
	plus<int>p;
	cout<<p(10,20)<<endl;
	return 0;
}

关系仿函数

功能描述:

  • 实现关系对比

仿函数原型:

  • template<class T> bool equal_to<T>     //等于
  • template<class T> bool not_equal_to<T>     //不等于
  • template<class T> bool greater<T>     //大于
  • template<class T> bool greater_equal<T>     //大于等于
  • template<class T> bool less<T>     //小于
  • template<class T> bool less_equal<T>     //小于等于

#include<iostream>
#include<vector>
#include<functional>
#include<algorithm>
using namespace std;

int main()
{
	vector<int>a;
	a.push_back(2);
	a.push_back(4);
	a.push_back(1);
	a.push_back(3);
	sort(a.begin(),a.end(),greater<int>());
	for(vector<int>::iterator it=a.begin();it!=a.end();it++)
		cout<<*it<<" ";
		
	return 0;
}

逻辑仿函数

功能描述:

  • 实现逻辑运算

仿函数原型:

  • template<class T> bool logical_and<T>     //逻辑与
  • template<class T> bool logical_or<T>     //逻辑或
  • template<class T> bool logical_not<T>     //逻辑非

#include<iostream>
#include<vector>
#include<functional>
#include<algorithm>
using namespace std;

int main()
{
	vector<bool>a;
	a.push_back(true);
	a.push_back(true);
	a.push_back(true);
	a.push_back(false);
	//sort(a.begin(),a.end(),greater<int>());
	for(vector<bool>::iterator it=a.begin();it!=a.end();it++)
		cout<<*it<<" ";
	cout<<endl;
	
	vector<bool>b;
	b.resize(a.size());//搬运之前一定要给目标容器开辟空间 
	
	transform(a.begin(),a.end(),b.begin(),logical_not<bool>());
	
	for(vector<bool>::iterator it=b.begin();it!=b.end();it++)
		cout<<*it<<" ";
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值