命名空間
變體
動作

std::unordered_map

出自 cppreference.com
< cpp‎ | container
 
 
 
 
定義於標頭檔 <unordered_map>
template<

    class Key,
    class T,
    class Hash = std::hash<Key>,
    class KeyEqual = std::equal_to<Key>,
    class Allocator = std::allocator<std::pair<const Key, T>>

> class unordered_map;
(1) (C++11 起)
namespace pmr {

    template<
        class Key,
        class T,
        class Hash = std::hash<Key>,
        class KeyEqual = std::equal_to<Key>
    > using unordered_map =
          std::unordered_map<Key, T, Hash, KeyEqual,
              std::pmr::polymorphic_allocator<std::pair<const Key, T>>>;

}
(2) (自 C++17 起)

std::unordered_map 是一種關聯式容器,包含具有唯一鍵(key)的鍵值對(key-value pairs)。元素的搜尋、插入與刪除具有平均常數時間複雜度。

在內部,元素不會以任何特定順序排序,而是組織成桶(buckets)。元素被放置在哪個桶中,完全取決於其鍵的雜湊值。具有相同雜湊碼的鍵會出現在同一個桶中。這使得個別元素的存取速度很快,因為一旦計算出雜湊值,它就直接指向元素所在的桶。

如果對映射(map)的鍵相等性謂詞傳入兩個鍵時返回 true,則這兩個鍵被視為等價(equivalent)。如果兩個鍵等價,雜湊函數必須為這兩個鍵返回相同的值。

std::unordered_map 符合 容器 (Container)分配器感知容器 (AllocatorAwareContainer)無序關聯式容器 (UnorderedAssociativeContainer) 的要求。

std::unordered_map 的所有成員函數皆為 constexpr:這表示可以在常數表達式的求值中建立並使用 std::unordered_map 物件。

然而,std::unordered_map 物件通常不能是 constexpr,因為任何動態配置的儲存空間都必須在同一個常數表達式求值中被釋放。

(C++26 起)

目錄

[編輯] 迭代器失效

作業 (Operations) 失效情況
所有唯讀操作、swapstd::swap 永不
clearrehashreserveoperator= 總是
insertemplaceemplace_hintoperator[] 僅當導致重雜湊(rehash)時
erase 僅針對被刪除的元素

[編輯] 註解

  • 交換(swap)函數不會使容器內的任何迭代器失效,但它們會使標示交換區域末端的迭代器失效。
  • 指向儲存在容器中之鍵或資料的參照與指標,僅在該元素被刪除時才會失效,即使對應的迭代器已經失效亦然。

[編輯] 模板參數

[編輯] 成員類型

類型 定義
key_type Key[編輯]
mapped_type T[編輯]
value_type std::pair<const Key, T>[編輯]
size_type 無號整數型別(通常為 std::size_t[編輯]
difference_type 有號整數型別(通常為 std::ptrdiff_t[編輯]
hasher Hash[編輯]
key_equal KeyEqual[編輯]
allocator_type Allocator[編輯]
reference value_type&[編輯]
const_reference const value_type&[編輯]
pointer std::allocator_traits<Allocator>::pointer[編輯]
const_pointer std::allocator_traits<Allocator>::const_pointer[編輯]
iterator LegacyForwardIterator ConstexprIterator(自 C++26)value_type[編輯]
const_iterator LegacyForwardIteratorConstexprIterator(自 C++26)const value_type[編輯]
local_iterator 一種迭代器類型,其類別、值、差異、指標和
參考類型與 iterator 相同。此迭代器
可用於遍歷單個桶,但不能跨桶遍歷[編輯]
const_local_iterator 一種迭代器類型,其類別、值、差異、指標和
參考類型與 const_iterator 相同。此迭代器
可用於遍歷單個桶,但不能跨桶遍歷[編輯]
node_type (C++17 起) 代表容器節點的 節點控制代碼 (node handle) 特化版本[編輯]
insert_return_type (C++17 起) 描述插入 node_type 結果的型別,為下列型別的特化:

template<class Iter, class NodeType>
struct /*未指定*/
{
    Iter     position;
    bool     inserted;
    NodeType node;
};

使用範本引數 iteratornode_type 實例化。[編輯]

[編輯] 成員函數

建構 unordered_map
(公開成員函式) [編輯]
解構 unordered_map
(公開成員函式) [編輯]
指派值給容器
(公開成員函式) [編輯]
回傳關聯的配置器
(公開成員函式) [編輯]
迭代器
回傳指向起點的反覆器
(公開成員函式) [編輯]
回傳指向終點的反覆器
(公開成員函式) [編輯]
容量
檢查容器是否為空
(公開成員函式) [編輯]
回傳元素個數
(公開成員函式) [編輯]
回傳最大可能的元素個數
(公開成員函式) [編輯]
修改器
清除內容
(公開成員函式) [編輯]
插入元素 或節點(C++17 起)
(公開成員函式) [編輯]
插入數值範圍元素
(公開成員函式) [編輯]
插入元素,若鍵已存在則指派給現有元素
(公開成員函式) [編輯]
原地建構元素
(公開成員函式) [編輯]
使用提示(hint)原地建構元素
(公開成員函式) [編輯]
若鍵不存在則原地插入;若鍵已存在則不執行任何操作
(公開成員函式) [編輯]
刪除元素
(公開成員函式) [編輯]
交換內容
(公開成員函式) [編輯]
(C++17)
從容器中提取節點
(公開成員函式) [編輯]
(C++17)
從另一個容器接合(splice)節點
(公開成員函式) [編輯]
查找
存取指定元素,並進行邊界檢查
(公開成員函式) [編輯]
存取或插入指定元素
(公開成員函式) [編輯]
回傳符合指定鍵的元素數量
(公開成員函式) [編輯]
尋找具有指定鍵的元素
(公開成員函式) [編輯]
(C++20)
檢查容器是否包含具有指定鍵的元素
(公開成員函式) [編輯]
回傳與特定鍵相匹配的元素範圍
(公開成員函式) [編輯]
Bucket 介面
返回指向指定桶開頭的迭代器
(公開成員函式) [編輯]
返回指向指定桶結尾的迭代器
(公開成員函式) [編輯]
返回桶的數量
(公開成員函式) [編輯]
返回桶的最大數量
(公開成員函式) [編輯]
返回特定桶中的元素數量
(公開成員函式) [編輯]
返回特定鍵所屬的桶索引
(公開成員函式) [編輯]
雜湊策略 (Hash policy)
返回每個桶的平均元素數量
(公開成員函式) [編輯]
管理每個桶的最大平均元素數量
(公開成員函式) [編輯]
預留至少指定數量的桶並重新產生雜湊表
(公開成員函式) [編輯]
為至少指定數量的元素預留空間並重新產生雜湊表
(公開成員函式) [編輯]
觀察器
返回用於雜湊鍵的函式
(公開成員函式) [編輯]
返回用於比較鍵是否相等的函式
(公開成員函式) [編輯]

[編輯] 非成員函數

(C++11)(C++11)(在 C++20 中移除)
比較 unordered_map 中的值
(函式模板) [edit]
特化 std::swap 演算法
(函式範本) [編輯]
移除所有符合特定條件的元素
(函式範本) [編輯]

推導指引

(自 C++17 起)

[編輯] 註解

功能測試巨集 數值 標準 功能
__cpp_lib_containers_ranges 202202L (C++23) 容器的範圍建構與插入
__cpp_lib_constexpr_containers 202502L (C++26) constexpr std::unordered_map

[編輯] 範例

#include <iostream>
#include <string>
#include <unordered_map>
 
int main()
{
    // Create an unordered_map of three strings (that map to strings)
    std::unordered_map<std::string, std::string> u =
    {
        {"RED", "#FF0000"},
        {"GREEN", "#00FF00"},
        {"BLUE", "#0000FF"}
    };
 
    // Helper lambda function to print key-value pairs
    auto print_key_value = [](const auto& key, const auto& value)
    {
        std::cout << "Key:[" << key << "] Value:[" << value << "]\n";
    };
 
    std::cout << "Iterate and print key-value pairs of unordered_map, being\n"
                 "explicit with their types:\n";
    for (const std::pair<const std::string, std::string>& n : u)
        print_key_value(n.first, n.second);
 
    std::cout << "\nIterate and print key-value pairs using C++17 structured binding:\n";
    for (const auto& [key, value] : u)
        print_key_value(key, value);
 
    // Add two new entries to the unordered_map
    u["BLACK"] = "#000000";
    u["WHITE"] = "#FFFFFF";
 
    std::cout << "\nOutput values by key:\n"
                 "The HEX of color RED is:[" << u["RED"] << "]\n"
                 "The HEX of color BLACK is:[" << u["BLACK"] << "]\n\n";
 
    std::cout << "Use operator[] with non-existent key to insert a new key-value pair:\n";
    print_key_value("new_key", u["new_key"]);
 
    std::cout << "\nIterate and print key-value pairs, using `auto`;\n"
                 "new_key is now one of the keys in the map:\n";
    for (const auto& n : u)
        print_key_value(n.first, n.second);
}

可能輸出

Iterate and print key-value pairs of unordered_map, being
explicit with their types:
Key:[BLUE] Value:[#0000FF]
Key:[GREEN] Value:[#00FF00]
Key:[RED] Value:[#FF0000]
 
Iterate and print key-value pairs using C++17 structured binding:
Key:[BLUE] Value:[#0000FF]
Key:[GREEN] Value:[#00FF00]
Key:[RED] Value:[#FF0000]
 
Output values by key:
The HEX of color RED is:[#FF0000]
The HEX of color BLACK is:[#000000]
 
Use operator[] with non-existent key to insert a new key-value pair:
Key:[new_key] Value:[]
 
Iterate and print key-value pairs, using `auto`;
new_key is now one of the keys in the map:
Key:[new_key] Value:[]
Key:[WHITE] Value:[#FFFFFF]
Key:[BLACK] Value:[#000000]
Key:[BLUE] Value:[#0000FF]
Key:[GREEN] Value:[#00FF00]
Key:[RED] Value:[#FF0000]

[編輯] 缺陷報告

下列更改行為的缺陷報告追溯應用於之前的 C++ 標準。

DR 應用於 出版時的行為 正確的行為
LWG 2050 C++11 referenceconst_referencepointer
const_pointer 的定義基於 allocator_type
基於 value_type
std::allocator_traits

[編輯] 參見

鍵值對的集合,按鍵雜湊
(類別範本) [編輯]
鍵值對(key-value pairs)的集合,按鍵排序,且鍵是唯一的
(類別樣板) [編輯]
(C++23)
適配兩個容器以提供按唯一鍵排序的鍵值對集合
(類別樣板) [編輯]
English Deutsch 日本語 中文(简体) 中文(繁體)