Most of time we used classes and sorts the collection of objects on different member variables. In these scenarios we have to write different-different Functor with respect to the classes. The following code provides a generic Functor which can be used with any class and can be used easily.

#include<iostream>

#include<vector>

#include <functional>

#include <algorithm>

template <typename T1,typename T2> class Functor

{

public:

Functor( T1 T2::* t):memPointer(t) {}

bool operator() ( const T2 & obj1, const T2 & obj )

{

return obj1.*memPointer < (obj.*memPointer);

}

T1 T2::* memPointer;

};

struct ABC{

double x;

double y;

};

int main()

{

std::vector<ABC> vec;

ABC ab;

ab.x = 9;

ab.y = 89;

vec.push_back(ab);

ab.x = 10;

ab.y = 10;

vec.push_back(ab);

ab.x = 5;

ab.y = 100;

vec.push_back(ab);

**Functor<double,ABC> bb(&ABC::x);**

**std::sort(vec.begin(), vec.end(), bb); **

std::vector<ABC>::iterator itr = vec.begin();

for (itr = vec.begin(); itr != vec.end(); ++itr)

std::cout << itr->x <<std::endl;

std::cout <<”——————–”<<std::endl;

**Functor<double,ABC> b2(&ABC::y);**

**std::sort(vec.begin(), vec.end(), b2); **

for (itr = vec.begin(); itr != vec.end(); ++itr)

std::cout << itr->y <<std::endl;

return 0;

}

**Out put:**

Sorted on member variable x

9

10

100

Sorted on member variable y

10

10

89