1. 程式人生 > >c++ STL 之 unorder_map及unorder_set使用自定義類作為key的方法

c++ STL 之 unorder_map及unorder_set使用自定義類作為key的方法


 

#include <iostream>
#include <string>
#include <unordered_map>
#include <unordered_set>
using namespace std;

struct RECT {
	int width;
	int height;

public:
	RECT(int a, int b)
	{
		width = a;
		height = b;
	}

};

//如果使用自定義的型別作為key,需要模板例項化hash結構體和過載相等判斷
namespace std
{
	template<>
	struct hash<RECT> : public _Bitwise_hash<RECT>
	{   // hash functor for RECT
	};
 
	inline bool operator == (const RECT &rc1, const RECT &rc2) _NOEXCEPT
	{
		return rc1.width == rc2.width && rc1.height == rc2.height;
	}
}

typedef std::unordered_map<std::string,std::string> stringmap;

void TestUnordered_map()
{
	//unordered_map
	unordered_map<RECT,int> Mymap;
	RECT tmp1(5,5),tmp2(3,3);
	Mymap.insert(unordered_map<RECT,int>::value_type(tmp1,4));
	Mymap.insert(pair<RECT,int>(tmp2,6));
	Mymap[RECT(2,2)] = 90;
	Mymap[tmp1] = 5;	//如果插入相同的鍵值,會覆蓋,以最後一個為主

	cout<<"unordered_map"<<endl;
	for(auto i = Mymap.begin(); i != Mymap.end();i++)
	{
		cout<<"key:"<<i->first.width << " "<<i->first.height<<"value:"<<i->second<<endl;
	}
	cout<<endl;

	//unordered_multimap
	unordered_multimap<RECT,int> MymapMul;
	RECT tmp3(5,5),tmp4(3,3);
	MymapMul.insert(unordered_multimap<RECT,int>::value_type(tmp3,4));
	MymapMul.insert(pair<RECT,int>(tmp3,3));
	MymapMul.insert(make_pair(tmp4,8));
	//MymapMul[RECT(4,4)] = 6; //不支援
	//MymapMul[tmp4] = 5;	//不支援

	cout<<"unordered_multimap"<<endl;
	for(auto i = MymapMul.begin(); i != MymapMul.end();i++)
	{
		cout<<"key:"<<i->first.width << " "<<i->first.height<<"value:"<<i->second<<endl;
	}

	cout<<"size: "<<MymapMul.size()<<endl;
	cout<<"empty:"<<MymapMul.empty()<<endl<<endl;
}


void TestUnordered_Set()
{
	//Unordered_map
	std::unordered_set<RECT> Myset;
	RECT tmp1(5,5),tmp2(3,3);
	Myset.insert(unordered_set<RECT>::value_type(tmp1));
	Myset.insert(tmp2);

	cout<<"unordered_set"<<endl;
	for(auto i = Myset.begin(); i != Myset.end();i++)
	{
		cout<<"key:"<<i->width<<i->height<<endl;
	}
	cout<<endl<<endl;
}