std::map中的仿函数

template<
class Key,
class T,
class Compare = std::less,
class Allocator = std::allocator<std::pair<const Key, T> >
> class map;

其中 std::less为一个functor(仿函数), 核心就在于在一个类或结构体中对()运算符进行重载。std::less详细定义为

template < class T> struct less{
bool operator() (const T& x, const T& y) const {return x<y;}
typedef T first_argument_type;
typedef T second_argument_type;
typedef bool result_type;
};

我们如果要对map里面的functor进行自定义,就需要参考以上形式来进行

举个例子

#include <iostream>     // std::cout 
#include <functional>   // std::less
#include <algorithm>    // std::sort
int main(void) 
{
	int foo[]={10,20,5,15,25}; 
	std::sort (foo, foo+5, std::less<int>()); // 5 10 15 20 25 
	for(int i = 0; i< 5; i++) 
		{ 
			std::cout << "value:"<<foo[i]<<std::endl; 
		} 
	return 0; 
}

这里的std::less()就是一个无名的实例

再举个例子

template<typename T> struct my_count1
{
    my_count1(T a)
    {
        threshold = a;
    }
    T threshold;
    bool operator()(T num)
    {
        return (num < threshold);
    }
};
 
int a[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
std::vector<int> v_a(a, a+10);
 
cout << "count: " << std::count_if(v_a.begin(), v_a.end(), my_count1<int>(8));

这里my_count1(8)也是一个无名的实例,不过是用int 8 去初始化构造函数的threshold=8
再将v_a中的每个值,依次作为num传入()operator
相当于
my_count1 sfs(8);
sfs(num) //根据num<threshold的结果,返回true或false

再看一个例子

template<typename T> class AddItem
{
public:
	T operator()(const T& item_a, const T& item_b)
	{
		return (item_a + item_b);
	}
};
 
template<class T> class MinusItem
{
public:
	T operator()(const T& item_a, const T& item_b)
	{
		return (item_a - item_b);
	}
};

调用

int b = AddItem<int>()(2, 8);
int c = MinusItem<int>()(2, 8);

相当于

AddItem<int>* additem = new AddItem<int>();
MinusItem<int>* minusitem = new MinusItem<int>();
int d = (*additem)(2, 8);
int e = (*minusitem)(2, 8);
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值