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);