std::hash_map的使用

std::hash_map的使用(基于VC2010)

 

std::hash_map的定义

// std::hash_map的定义

template<class _Kty,	// Key
	class _Ty,			// Value
	class _Tr = hash_compare<_Kty, less<_Kty> >,	// 哈希比较器(里面也调用了普通的比较器)
	class _Alloc = allocator<pair<const _Kty, _Ty> > >	// 内存分配器
	class hash_map : public _Hash<_Hmap_traits<_Kty, _Ty, _Tr, _Alloc, false> >	// 父类(哈希)
{
......
}


std::hash_map的哈希比较器

// std::hash_map的哈希比较器

// 哈希比较器里面应该与哈希算法相关

// 哈希比较器里面还是使用了和std::map一样的默认的less比较器.

template<class _Kty, class _Pr = less<_Kty> >
class hash_compare
{	// traits class for hash containers
public:
	enum
	{	// parameters for hash table
		bucket_size = 1		// 0 < bucket_size
	};
	
	// construct with default comparator
	hash_compare() : comp()
	{}
	
	// construct with _Pred comparator
	hash_compare(_Pr _Pred) : comp(_Pred)
	{}

	// Hash function
	// 该函数的实现不是很懂(应该是哈希算法的一部分, 桶之类的), 暂时不深究
	size_t operator()(const _Kty& _Keyval) const
	{	// hash _Keyval to size_t value by pseudorandomizing transform
		long _Quot = (long)(hash_value(_Keyval) & LONG_MAX);
		ldiv_t _Qrem = _CSTD ldiv(_Quot, 127773);

		_Qrem.rem = 16807 * _Qrem.rem - 2836 * _Qrem.quot;
		if (_Qrem.rem < 0)
			_Qrem.rem += LONG_MAX;
		return ((size_t)_Qrem.rem);
	}

	bool operator()(const _Kty& _Keyval1, const _Kty& _Keyval2) const
	{	// test if _Keyval1 ordered before _Keyval2
		return (comp(_Keyval1, _Keyval2));					// 这里最终还是使用了less比较器
	}

protected:
	_Pr comp;	// the comparator object
};

 

使用

// 看使用代码

#include "stdafx.h"
#include <string>
#include <hash_map>

// 定义自己std::map比较器
typedef std::string* PSTDString;

template<class _Ty>
struct PLess	
{
	// functor for operator<
	bool operator()(const _Ty& pLeft, const _Ty& pRight) const
	{
		// apply operator< to operands
		return (*pLeft) < (*pRight);		// 这个比较器与默认比较器不同的地方
	}
};

int _tmain(int argc, _TCHAR* argv[])
{
	// 这里还是使用std::hash_map的std::hash_compare. 但是
	// std::hash_compare内部最终的比较使用自定义的比较器.
	std::hash_map<PSTDString, int, std::hash_compare<PSTDString, PLess<PSTDString> > > PStringToIntMap1;

	// 这里的使用和std::map一样
	std::string str1 = "1";
	std::string str2 = "2";
	std::string str3 = "3";
	PStringToIntMap1[&str1] = 3;
	PStringToIntMap1[&str2] = 2;
	PStringToIntMap1[&str3] = 1;

	return 0;
}

四. 与std::map的比较

std::hash_map的时间复杂度是O(1) -- O(N) : 不稳定, 但比map快.

std::map的时间复杂度是O(log2N) : 比hash_map慢, 但稳定.
看你的使用场合. STL中使用上完全可以互相替换.

你可能感兴趣的:(std::hash_map的使用)