関数オブジェクトについて

タイトルにそれを説明するためのものです。

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

表題の要件は、N、Sの発注からアレイ出力の大きさによって指定されます。
私は、コードはこれです起動します。

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

int型からの結果は、<文字列、int型(*)(定数文字列&、constの文字列&)>型変換関数をまったくクローサーを言わないように。私はかなり奇妙だ、それはT1にint型ではないのですか?どのような地獄であるT2のその後奇妙なタイプ?年齢のためにトスして、実際にオブジェクトを作成することであることを発見しました。これは、オブジェクトへの自然や関数オブジェクトであるが、それは()のみ、オーバーロードと呼ばれます。()ここではコンペア機能の並べ替えの役割を果たしていると、パラメータがconstの無効とされた* E1、constのボイド* e2は多分、他のパラメータがあってはなりません。私は構造体を記述する必要はないので......まあすぐに無知な、とは、2つのパラメータを設定する構造体にコンストラクタを書きました。結果は、CONSTのvoid *に* ITERを_tp変換するために、どのアルゴリズムを言うために決して持っているので、私はE1を渡すように変更され、E2の参照、最後超える結果...... ACコード:

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

最後に、ポインタを渡すのqsortと同じではなく、直接値でのqsortと比較関数の並べ替えを考え出すの種類の違いを確認してください。T1&T1は、これまでに変更することができます。

おすすめ

転載: blog.csdn.net/weixin_44288817/article/details/88863594