Home Item 4 (2/2) - unordered_map (English)
Post
Cancel

Item 4 (2/2) - unordered_map (English)

c++ New Container Type: unordered_map

In C#, you have Dictionary, and Python also offers similar key-value mapping data structures to use. How about C++? Well, C++11 provides unordered_map for coders to utilize. The reason it’s called unordered is because it’s implemented based on a hash table, which does not guarantee the order of elements. Check it out below!

Let’s dive straight into the 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;

    // Insert some key-value pairs
    umap["Kobe"] = 24;
    umap["Luka"] = 77;
    umap["Shaq"] = 34;

    // Iterate through the map using iterators and print each key-value pair
    for (const auto& pair : umap) {
        std::cout << pair.first << ": " << pair.second << std::endl;
    }

    return 0;
}

The order is not guaranteed (my favorite Kobe ended up behind Luka…)

onlinegdb

Execution Result

Desktop View

Usage:

when an unordered mapping (associative array) is needed, and efficiency in lookup time is required, std::unordered_map can be used. It provides fast lookup operations with an average time complexity of O(1).

☝ツ☝

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

👈 ツ 👍