Home Item 4 (2/2)- unordered_map (中文)
Post
Cancel

Item 4 (2/2)- unordered_map (中文)

c++ 新的容器類型: unordered_map

C# 有 Dictionary 可以用,python 也有這種 key value mapping 的資料結構可以使用。 C++ 呢 ? C++ 11 提供 unordered_map 供 coder 使用。unordered_map 之所以被稱為 unordered ,是因為它是基於哈希表(hash table)實現的,而哈希表不保證元素的順序往下看吧。

直接看 code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <unordered_map>
#include <string>

int main() {
    // Create an unordered map that maps strings to integers
    std::unordered_map<std::string, int> umap;

    // 插入一些鍵值對
    umap["Kobe"] = 24;
    umap["Luka"] = 77;
    umap["Shaq"] = 34;

    // 使用迭代器遍歷映射並打印每個鍵值對
    for (const auto& pair : umap) {
        std::cout << pair.first << ": " << pair.second << std::endl;
    }

    return 0;
}

順序不保證(我最愛的 Kobe 竟然排在 Luka 後面…)

onlinegdb

執行結果

Desktop View

使用時機:

當需要一個無序的映射(關聯陣列),並且對查找時間的效率要求較高時,可以使用 std::unordered_map。它提供了快速的查找操作,時間複雜度為平均 O(1)。

☝ツ☝

This post is licensed under CC BY 4.0 by the author.

👈 ツ 👍