c++ STL 之 unorder_map及unorder_set使用自定义类作为key的方法


 

#include 
#include 
#include 
#include 
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 : public _Bitwise_hash
	{   // 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 stringmap;

void TestUnordered_map()
{
	//unordered_map
	unordered_map Mymap;
	RECT tmp1(5,5),tmp2(3,3);
	Mymap.insert(unordered_map::value_type(tmp1,4));
	Mymap.insert(pair(tmp2,6));
	Mymap[RECT(2,2)] = 90;
	Mymap[tmp1] = 5;	//如果插入相同的键值,会覆盖,以最后一个为主

	cout<<"unordered_map"<first.width << " "<first.height<<"value:"<second< MymapMul;
	RECT tmp3(5,5),tmp4(3,3);
	MymapMul.insert(unordered_multimap::value_type(tmp3,4));
	MymapMul.insert(pair(tmp3,3));
	MymapMul.insert(make_pair(tmp4,8));
	//MymapMul[RECT(4,4)] = 6; //不支持
	//MymapMul[tmp4] = 5;	//不支持

	cout<<"unordered_multimap"<first.width << " "<first.height<<"value:"<second< Myset;
	RECT tmp1(5,5),tmp2(3,3);
	Myset.insert(unordered_set::value_type(tmp1));
	Myset.insert(tmp2);

	cout<<"unordered_set"<width<height<

 

你可能感兴趣的:(STL)