C++ 裡 key-value 形式的容器不少:map、hash_map、unordered_map,以及自己實作的 vector_map。以下說明基本用法與選擇依據。
#include <iostream>
#include <map>
using namespace std;
typedef std::map<int, string> Map;
typedef Map::iterator MapIt;
int main() {
Map *map = new Map();
int key;
string value;
while (cin >> key >> value) {
map->insert(make_pair(key, value));
}
for (MapIt it = map->begin(); it != map->end(); ++it)
cout << "key:" << it->first << " value:" << it->second << endl;
delete map;
return 0;
}
map 以紅黑樹實作,查詢時間落在 O(lg n) 到 O(2 log n) 之間,建構成本較高,因此適合「插入與查詢交錯」的情境。若是先大量插入、之後才查詢,vector_map 會更划算。
C++ 標準庫沒有 vector_map,得自己實作。思路是用 vector 存資料,插入完成後統一排序,查詢時用二分搜尋。在先插後查的前提下,效能明顯優於 map,原因有四:
map 的 key 可以是自訂結構,但必須重載 < 運算子:
typedef struct _Key {
_Key(int *p, int l) {
len_ = l;
for (int i = 0; i < l; ++i)
p_[i] = p[i];
}
bool operator<(const _Key &rs) const {
if (len_ == rs.len_) {
for (int i = 0; i < len_; ++i)
return p_[i] < rs.p_[i];
return false;
} else
return len_ < rs.len_;
}
int p_[MaxLen];
int len_;
} Key;
typedef std::map<Key, vector<int> *> MyMap;
另外,若使用自訂比較器(如範例中的 KeyCmp),map 的 value 型別與 key 型別不必綁死,比較器只要保證嚴格弱序即可,這一點在自製容器時要特別小心。