hash_map和map的用法很相似,只是底層機制有所不同。
hash_map容器采用的底層機制是hash table代碼:
~~~
template <class Key, class T, class HashFcn = hash<Key>,
class EqualKey = equal_to<Key>,
class Alloc = alloc>
class hash_map
{
private:
typedef hashtable<pair<const Key, T>, Key, HashFcn,
select1st<pair<const Key, T> >, EqualKey, Alloc> ht;
ht rep; // 底層機制——hash table
....
}
~~~
注意,hashtable類型的第一個類型參數是pair,繼續跟蹤hashtable代碼:
~~~
template <class Value, class Key, class HashFcn,
class ExtractKey, class EqualKey,
class Alloc>
class hashtable { // hash table數據結構
public:
typedef Key key_type;
typedef Value value_type;
....
typedef __hashtable_node<Value> node;
typedef simple_alloc<node, Alloc> node_allocator; // 空間配置器
vector<node*,Alloc> buckets; // 桶的集合
....
}
~~~
可以看出,Value或value_type的實際類型是一個pair,那么一個node中也存儲了一個pair,而vector中的bucket還是指針不變。即每個bucket指向一串nodes,每個node中存放一個pair<key, value>。這和map容器是類似的,map容器底層的紅黑樹中,每個節點也是存儲了一個pair。
下面是測試代碼:
~~~
#include <iostream>
#include <hash_map>
#include <cstring>
using namespace std;
using namespace __gnu_cxx;
struct eqstr {
bool operator() (const char *s1, const char *s2) const
{ return strcmp(s1, s2) == 0; }
};
int main()
{
hash_map<const char*, int, hash<const char *>, eqstr> m;
// 兩種插入方法
m["hello"] = 123;
m["byebye"] = 234;
m["test"] = 345;
m.insert(pair<const char *, int>("a", 222));
hash_map<const char*, int, hash<const char *>, eqstr>::iterator iter = m.begin();
for ( ; iter != m.end(); ++iter)
cout << iter->first << ' ' << iter->second << endl;
return 0;
}
~~~
運行結果:

由于hash_map提供的默認鍵值比較標準為equal_to:
~~~
template <class T>
struct equal_to : public binary_function<T, T, bool> {
bool operator()(const T& x, const T& y) const { return x == y; }
};
~~~
這個仿函數只是簡單的拿兩個值進行比較,如果傳入的key為const char *,那么比較的將會是兩個地址,這不是我們想要的。正確的字符串比較應該是逐個字符進行比較,這就是為什么要定義eqstr的原因。
從運行結果也能夠看出,和hash_set一樣,hash_map內的元素無特定排序。
參考:
《STL源碼剖析》 P275.
- 前言
- 順序容器 — heap
- 關聯容器 — 紅黑樹
- 關聯容器 — set
- 關聯容器 — map
- 關聯容器 — hashtable
- 關聯容器 — hash_set
- 關聯容器 — hash_map
- 算法 — copy
- 順序容器 — stack
- 順序容器 — queue
- 順序容器 — priority_queue
- 順序容器 — slist
- construct()和destroy()
- 空間配置器
- 函數適配器
- 迭代器以及“特性萃取機”iterator_traits
- 算法 — partial_sort
- 算法 — sort
- 仿函數
- 適配器(adapters)
- C++簡易vector
- C++簡易list
- STL算法實現
- C++模板Queue