std :: map of functor

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

Wherein std :: less of a functor (functor), lies on the core () operator overloaded in a class or structure. std :: less detailed definitions as

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

If you want us to map the inside of the functor customize, you need to refer to the above form

for example

#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; 
}

Here std :: less () is an instance of a nameless

Another example

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

Here my_count1 (8) is also an instance of unknown, but is to initialize the threshold int 8 constructor = 8
each value in v_a then sequentially passed as num () operator
corresponding to
my_count1 SFS (8);
SFS (num) // the results num <threshold, returning true or false

Look at an example

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

transfer

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

Equivalent to

AddItem<int>* additem = new AddItem<int>();
MinusItem<int>* minusitem = new MinusItem<int>();
int d = (*additem)(2, 8);
int e = (*minusitem)(2, 8);
Published 31 original articles · won praise 18 · views 6036

Guess you like

Origin blog.csdn.net/weixin_40027284/article/details/84894533