std::hash_map的使用
2014-11-25 17:38
281 查看
std::hash_map的使用(基于VC2010)
// 哈希比较器里面应该与哈希算法相关
// 哈希比较器里面还是使用了和std::map一样的默认的less比较器.
: 不稳定, 但比map快.
std::map的时间复杂度是O(log2N) : 比hash_map慢, 但稳定.
看你的使用场合. STL中使用上完全可以互相替换.
一. 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中使用上完全可以互相替换.
相关文章推荐
- 一个hash_map使用错误
- 如何统计出一篇文章出现的文字个数? (高级) (使用std::map)
- Linux和MinGW(ZOJ)上hash_set和hash_map使用方案
- [STL] __gnu_cxx::hash_map使用中的一些问题
- STL hash_map使用
- ACE_Hash_Map的使用示例
- 在GCC和Visual Studio中使用hash_map
- hash_map的使用方法
- GCC中使用hash_map
- std::map的使用
- vs 2003 中hash_map使用方法
- std::map的简单使用例子
- 关于在toj上使用hash_map(回复黄冶)
- 使用STL的hash_map要点
- 使用 std::map 查找 IP 范围
- (原創) 如何使用subscripting的方式新增std::map? (C/C++) (STL)
- std::map使用出错_Nodeptr _Pnode = _Root();
- hash_map的使用
- hash_map的使用备忘
- VC中使用STL的hash_map