Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

C++ 各種 map 容器的用法與差異比較

C++ 裡 key-value 形式的容器不少:map、hash_map、unordered_map,以及自己實作的 vector_map。以下說明基本用法與選擇依據。

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 的特性

map 以紅黑樹實作,查詢時間落在 O(lg n) 到 O(2 log n) 之間,建構成本較高,因此適合「插入與查詢交錯」的情境。若是先大量插入、之後才查詢,vector_map 會更划算。

vector_map 為何更快

C++ 標準庫沒有 vector_map,得自己實作。思路是用 vector 存資料,插入完成後統一排序,查詢時用二分搜尋。在先插後查的前提下,效能明顯優於 map,原因有四:

  1. vector 是線性儲存,map 是二叉樹,前者的記憶體局部性更好。
  2. vector 可以一次配置大塊記憶體;map 每次插入都要配置一個節點,且節點內含指向子節點的指標等冗餘資料。
  3. vector 只在最後排序一次;map 每次 insert 都要做一次查找與樹的旋轉。
  4. vector_map 的二分查找穩定在 O(lg n),map 則在 O(lg n)~O(2 log n) 之間波動。

自訂型別當 key

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 型別不必綁死,比較器只要保證嚴格弱序即可,這一點在自製容器時要特別小心。

Copyright © Linux教程網 All Rights Reserved