仿函数 functor

仿函数 functor

  • 仿函数一般不会单独使用,主要是为了搭配STL算法使用。补充STL算法的很好的方式
  • 函数指针不能满足STL对抽象性的要求,不能满足软件积木的要求无法和STL其他组件搭配:
  • 本质就是类重载了一个operator(),创建一个行为类似函数的对象


#include <vector>
#include <list>
#include <queue>
#include <iostream>
#include <stack>
#include <map>
#include <algorithm>
#include <functional>

using namespace std;


void Display(int a) {
	cout << a << " ";
}

bool MySort(int a, int b)
{
	return  a > b;
}

template<class T>
inline void DisplayT(T const& a) {
	cout << a << " ";
}

template<class T>
inline bool MySortT(T const& a, T const& b)
{
	return  a > b;
}

struct SortF
{
	bool operator()(int a, int b)
	{
		return a > b;
	}
};

struct DisplayF
{
	void operator()(int a)
	{
		cout << a << " ";
	}
};

//C++ 仿函数模板
template<class T>
struct SortTF
{
	inline bool operator() (T const& a, T const& b) const
	{
		return a > b;
	}	
};

template<class T>
struct DisplayTF
{
	inline void operator() (T const& a) const
	{
		cout << a << " ";
	}
};


int main() {
	// C++ 方法
	int arr[] = { 4,3,2,1,5 };
	sort(arr, arr + 5, MySort);
	for_each(arr, arr + 5, Display);
	cout << endl;

	// C++ 泛型
	int arr2[] = { 4,3,2,1,5 };
	sort(arr2, arr2 + 5, MySortT<int>);
	for_each(arr2, arr2 + 5, DisplayT<int>);
	cout << endl;

	//C++ 仿函数
	int arr3[] = { 4,3,2,1,5 };
	sort(arr3, arr3 + 5, SortF());
	for_each(arr3, arr3 + 5, DisplayF());
	cout << endl;

	//C++ 仿函数模板
	int arr4[] = { 4,3,2,1,5 };
	sort(arr4, arr4 + 5, SortTF<int>());
	for_each(arr4, arr4 + 5, DisplayTF<int>());
	cout << endl;

	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小叶柏杉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值