About function object

To the title to illustrate it.

#include <iostream>
#include <cmath>
#include <algorithm>
#include <string>
using namespace std;
template <class T1,class T2>
struct Closer {
};

int Distance1(int n1,int n2) {
	return abs(n1-n2);
}
int Distance2(const string & s1, const string & s2)
{
	return abs((int)s1.length()- (int) s2.length());
}
int a[10] = { 0,3,1,4,7,9,20,8,10,15};
string b[6] = {"American","Jack","To","Peking","abcdefghijklmnop","123456789"};
int main()
{
	int n;string s;
	while( cin >> n >> s ) {
		sort(a,a+10,Closer<int ,int (*)(int ,int)> (n,Distance1));
		for(int i = 0;i < 10; ++i)
			cout << a[i] << "," ;
		cout << endl;
		sort(b,b+6,Closer<string,int (*)(const string &,const string &  )> (s,Distance2)); 
		for(int i = 0;i < 6; ++i)
			cout << b[i] << "," ;
		cout << endl;
	}
	return 0;
}

Title requirement is designated by n, the size of the array output from the ordering of s.
I start the code is this:

bool operator()(T1 x, T2 func, const void *e1, const void *e2)const {
		T1 *p1 = (T1 *)e1;
		T1 *p2 = (T1 *)e2;
		if (func(x, *p1) > func(x, *p2)) return true;
		if (func(x, *p1) < func(x, *p2)) return false;
		if (func(x, *p1) == func(x, *p2)) {
			if (*p1 < *p2) return true;
			if (*p1 > *p2) return false;
		}
	}

Results from int to say no Closer <string, int (*) (const string &, const string &)> type conversion functions. I am quite strange, is not on the T1 int it? Then a strange type of T2 that is what the hell? Toss for ages, and then discovered that in fact there is in it to create an object. That is, the nature or function object to an object, but called it overloaded () only. The () here is to play the role of a sort which compare function, parameter is const void * e1, const void * e2 maybe, there should be no other parameters. As I do not need to write a struct ...... Well ignorant, and quickly wrote a constructor in a struct which set up two parameters. The result has in no way to say which algorithm to convert _tp * iter into const void *, so I changed to pass e1, e2 reference, the results over the last ...... AC Code:

    T1 x;
	T2 func;
	Closer(T1 x1,T2 func1):x(x1),func(func1) { }
	const bool operator()(T1 &e1,T1 &e2){
		T1 *p1= &e1;
		T1 *p2= &e2;
		if(func(x,*p1)>func(x,*p2)) return false;
		if(func(x,*p1)<func(x,*p2)) return true;
		if(func(x,*p1)==func(x,*p2)){
			if(*p1<*p2) return true;
			if(*p1>*p2) return false;
		}
	}

Finally, check the difference between qsort and sort of figuring out the sort of compare function is not the same as qsort pass pointer, but directly by value. The T1 & T1 is able to change ever.

Guess you like

Origin blog.csdn.net/weixin_44288817/article/details/88863594