内建函数对象

165 阅读1分钟

内建函数对象意义

概念:

  • STL内建了一些函数对象

分类:

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

用法:

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

算数仿函数

功能描述:

  • 实现四则远算
  • 其中negate是一团运算,其他都是二元运算

函数原型:

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

示例:

//nagate	一元仿函数
void test01()
{

	negate<int> n;

	cout << n(50) << endl;
}

//plus	二元仿函数 加法
void test02()
{
	//加法
	plus<int>p;

	cout << p(10, 20) << endl;

	//减法
	minus<int>m;

	cout << m(100, 20) << endl;

	//乘法
	multiplies<int>mu;

	cout << mu(10, 20) << endl;

	//除法
	divides<int>d;

	cout << d(20, 20) << endl;

	//取模
	modulus<int>mo;

	cout << mo(10, 20) << endl;


}

关系仿函数

函数原型:

  • template bool equal_to //等于
  • template bool not_equal_to //不等于
  • template bool greater //大于
  • template bool greater_equal //大于等于
  • template bool less //小于
  • template bool less_equal //小于等于

示例:

class MyCompare
{
public:
	bool operator()(int v1, int v2)
	{
		return v1 > v2;
	}
};

//大于 greater
void test01()
{
	vector<int>v;
	v.push_back(20);
	v.push_back(50);
	v.push_back(10);
	v.push_back(30);
	v.push_back(40);

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

	//降序
	//sort(v.begin() , v.end(), MyCompare());
	// greater<int>()	内建函数对象
	sort(v.begin(), v.end(), greater<int>());
	for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
	{
		cout << *it << " ";
	}
	cout << endl;
}

逻辑仿函数

函数原型:

  • template bool logical_and //逻辑与
  • template bool logical_or //逻辑或
  • template bool logical_not //逻辑非

示例:

void test01()
{
	vector<bool>v;
	v.push_back(true);
	v.push_back(true);
	v.push_back(false);
	v.push_back(true);
	v.push_back(false);

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

	//利用逻辑非	将容器v搬运到	容器v2中,并执行取反操作
	vector<bool>v1;
	v1.resize(v.size());
	// transform  必须先开辟空间指定大小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;
}