天天看点

内建函数对象

内建函数对象

概念:STL中内建一些函数对象

分类:

算术仿函数

关系仿函数

逻辑仿函数

需要引入头文件 #include < functional>

1.算术仿函数

有加减乘除,取模,取反(英文:plus,minus,multiplies,divides,modulus,negate)

模板

template(class T) T negated < T> //(加)

其中只有取反为一元运算,其他为二元运算

例如取反调用:

negate<int> n;   //一元参数只有一个,二元参数也只有一个
cout<<n(10)<<endl;  //输出-10
           

例如加法调用:

plus<int> n;    //二元参数也只有一个
cout<<n(10,20)<<endl; //输出3
           
2.关系仿函数

模板:

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 > //小于等于

例子,内建函数放入sort中:

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

void test()
{
	vector<int> v;
	v.push_back(10);
	v.push_back(15);
	v.push_back(30);
	v.push_back(40);
	for(vector<int>::iterator it = v.begin();it!=v.end();it++)
	{
		cout<<*it<<" ";
	}
	cout<<endl;	
	//使sort按降序来排
	sort(v.begin(),v.end(),greater<int>());  //放入内建函数大于

	for(vector<int>::iterator it = v.begin();it!=v.end();it++)
	{
		cout<<*it<<" ";
	}
	cout<<endl;
}

int main()
{
	test();
	system("pause");
	return 0;
}
           

运行结果:

内建函数对象
3.逻辑仿函数

template< class T>bool logical_and < T> //逻辑与

template< class T>bool logical_or < T> //逻辑或

template< class T>bool logical_not < T> //逻辑非

搬运算法:

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

void test()
{
	vector<bool> v;  //布尔类型的容器
	v.push_back(true);
	v.push_back(true);
	v.push_back(false);
	v.push_back(false);
	for(vector<bool>::iterator it = v.begin();it!=v.end();it++)
	{
		cout<<*it<<" ";
	}
	cout<<endl;

	vector<bool> v2;
	v2.resize(v.size());   //先开辟空间

	transform(v.begin(),v.end(),v2.begin(),logical_not<bool>());  //利用搬运算法,搬运前首先要开辟容量

	for(vector<bool>::iterator it = v2.begin();it!=v2.end();it++)
	{
		cout<<*it<<" ";
	}
}

int main()
{
	test();
	system("pause");
	return 0;
}
           

继续阅读