热门问题
时间线
聊天
视角

無序關聯容器 (STL)

来自维基百科,自由的百科全书

Remove ads

C++程序設計語言中,unordered_mapunordered_multimapunordered_setunordered_multiset標準模板庫(STL)提供的一類無序關聯容器(unordered associative containers)。是通過哈希表實現的數據結構。無序是指元素的名字(或者鍵值)的存儲是無序的;這與用平衡二叉樹實現的元素名字是有序存儲的「關聯容器」是相對概念。

歷史

SGISTL提供了hash_map, hash_set, hash_multimap, hash_multiset等類模板。[1]由於其有用性,很快其它的C++編譯器也支持了這一特性,如GCClibstdc++[2] 以及MSVC (在stdext命名空間)。

C++ TR1語言標準中提出了增加hash_*類模板[3],最終接受為unordered_*[4] Boost C++ Libraries也提供了一種實現。<boost/unordered_map.hpp>.[5]

類成員函數

頭文件<unordered_map>中定義了類模板unordered_map。並滿足容器頁面存檔備份,存於網際網路檔案館概念,這意味着它支持begin()end()size()max_size()empty()swap()等方法。

更多信息 unordered_set (C++11), unordered_map (C++11) ...
Remove ads

例子

#include <iostream>
#include <string>
#include <unordered_map>
 
int main()
{
    std::unordered_map<std::string, int> months;
    months["january"] = 31;
    months["february"] = 28;
    months["march"] = 31;
    months["april"] = 30;
    months["may"] = 31;
    months["june"] = 30;
    months["july"] = 31;
    months["august"] = 31;
    months["september"] = 30;
    months["october"] = 31;
    months["november"] = 30;
    months["december"] = 31;
    std::cout << "september -> " << months["september"] << std::endl;
    std::cout << "april     -> " << months["april"] << std::endl;
    std::cout << "december  -> " << months["december"] << std::endl;
    std::cout << "february  -> " << months["february"] << std::endl;

    //判断map中是否包含一个键值,没有直接做此事的成员函数。类似其他的STL容器,解决办法是:
    if( months.find("no_value") == months.end() )
    {
          printf("No such key in the map.");
    }
    return 0;
}

定製哈希函數

定製的哈希函數的參數為到定製類型的const引用,返回類型為size_t

struct X{int i,j,k;};

struct hash_X{
  size_t operator()(const X &x) const{
    return hash<int>()(x.i) ^ hash<int>()(x.j) ^ hash<int>()(x.k);
  }
};

定製哈希函數作為std::unordered_map的模板參數使用。

 std::unordered_map<X,int,hash_X> my_map;

或者通過特化std::hash來使用。

namespace std {
    template <>
        class hash<X>{
        public :
        size_t operator()(const X &x ) const{
            return hash<int>()(x.i) ^ hash<int>()(x.j) ^ hash<int>()(x.k);
        }
    };
}

//...
 std::unordered_map<X,int> my_map;
Remove ads

參考文獻

Loading content...
Loading related searches...

Wikiwand - on

Seamless Wikipedia browsing. On steroids.

Remove ads