STL: unordered_map 自定義鍵值使用


使用Windows下 RECT 類型做unordered_map 鍵值

1. Hash 函數

 計算自定義類型的hash值。

struct hash_RECT 
{
	size_t operator()(const RECT &rc) const
	{
		return std::_Hash_seq((const unsigned char *)&rc, sizeof(RECT));
	}
};

  

2. 相等函數

 哈希需要處理碰撞,意味着必須判斷兩個自定義類型對象是否相等。

struct cmp_RECT
{
	bool operator()(const RECT &rc1, const RECT &rc2) const
	{
		return rc1.left == rc2.left && rc1.top == rc2.top
			&& rc1.right == rc2.right && rc1.bottom == rc2.bottom;
	}
};

  

3. 使用

std::unordered_map<RECT, std::wstring, hash_RECT, cmp_RECT> G_mapText

 這樣感覺好長,我們接着往下看。

 

4. 使用STL提供的模板

stl中有這么兩個模板

	// TEMPLATE STRUCT _Bitwise_hash
template<class _Kty>
	struct _Bitwise_hash
	{	// hash functor for plain old data
	typedef _Kty argument_type;
	typedef size_t result_type;

	size_t operator()(const _Kty& _Keyval) const
		{	// hash _Keyval to size_t value by pseudorandomizing transform
		return (_Hash_seq((const unsigned char *)&_Keyval, sizeof (_Kty)));
		}
	};

	// TEMPLATE STRUCT hash
template<class _Kty>
	struct hash
		: public _Bitwise_hash<_Kty>
	{	// hash functor for enums
	static const bool _Value = __is_enum(_Kty);
	static_assert(_Value,
		"The C++ Standard doesn't provide a hash for this type.");
	};

所以我們可以直接這么寫:

std::unordered_map<RECT, std::wstring, std::hash<RECT>, cmp_RECT> G_mapText

這樣就可以丟掉上面的 hash函數 “hash_RECT”  

這樣寫感覺還是比較長,我們再來看看另一種方法。

 

4. 實例化模板

直接實例化模板,這樣的話使用 unordered_map 時便不用再指定 Hash 函數,但要求必須為 KEY 重載 operator ==,實例化模板如下:

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.left == rc2.left && rc1.top == rc2.top
			&& rc1.right == rc2.right && rc1.bottom == rc2.bottom;
	}
}

這樣我們就可以直接這么寫了:

std::unordered_map<RECT, std::wstring> G_mapText;

 

實例代碼:

 

至此 unordered_map 自定義鍵值的用法結束。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM