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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013919153/article/details/82463966

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

猜你喜欢

转载自blog.csdn.net/u013919153/article/details/82463966