1. 程式人生 > >c++ map自定義排序

c++ map自定義排序

在c++中用到map時,如果key是自定義的struct,那麼需要自己定義比較函式。因為只有基本型別有預設的比較方法。

typedef struct myKey
{
	int nId;
	int nVersion;
	int nNote;
}myKey;

///自定義map的value
typedef struct myValue
{
	string strText;
}myValue;

struct cmp_key
{
	bool operator()(const myKey &k1,const myKey &k2) const
	{
		if(k1.nId != k2.nId)
		{
			return k1.nId < k2.nId;
		}

		if(k1.nVersion != k2.nVersion)
		{
			return k1.nVersion < k2.nVersion;
		}

		if(k1.nNote != k2.nNote)
		{
			return k1.nNote < k2.nNote;
		}

		return false;
	}
};

int _tmain(int argc, _TCHAR* argv[])
{
	map<myKey,myValue,cmp_key> mymap;
	myKey k1;
	k1.nId = 1;
	k1.nVersion = 2;
	k1.nNote = 3;
	myValue v1;
	v1.strText = "k1: id=1 version=2 note=3";

	myKey k2;
	k2.nId = 2;
	k2.nVersion = 2;
	k2.nNote = 3;
	myValue v2;
	v2.strText = "k1: id=2 version=2 note=3";

	myKey k3;
	k3.nId = 2;
	k3.nVersion = 2;
	k3.nNote = 5;
	myValue v3;
	v3.strText = "k1: id=2 version=2 note=5";

	mymap[k1] = v1;
	mymap[k2] = v2;
	mymap[k3] = v3;

	for(auto it = mymap.begin(); it != mymap.end(); ++it)
	{
		cout << it->second.strText.c_str() << endl;
	}
	return 0;
}
輸出:

k1: id=1 version=2 note=3
k1: id=2 version=2 note=3
k1: id=2 version=2 note=5
對value排序的話,用vector<pair>代替。