C++ Standard Library<unordered_map>

In C++,<unordered_map>Is part of the Standard Template Library (STL), providing a hash table-based key-value pair container.

andstd::mapDifferent,unordered_mapDoes not guarantee the ordering of elements, but typically provides faster lookup speed.

unordered_mapIs an associative container that stores key-value pairs, where each key is unique.unordered_mapUses a hash table to store elements, which gives it average constant time complexity for lookup, insertion, and deletion operations.

Syntax

The following areunordered_mapbasic syntax:

#include <unordered_map>

std::unordered_map<key_type, value_type> map_name;
  • key_typeis the type of the key.
  • value_typeis the type of the value.

Constructor

unordered_mapIt can be constructed in multiple ways:

// 默认构造
std::unordered_map<int, std::string> myMap;

// 构造并初始化
std::unordered_map<int, std::string> myMap = {{1, "one"}, {2, "two"}};

// 构造并指定初始容量
std::unordered_map<int, std::string> myMap(10);

// 构造并复制另一个 unordered_map
std::unordered_map<int, std::string> anotherMap = myMap;

Basic Operations

Insert elements:

myMap.insert({3, "three"});

Access elements:

std::string value = myMap[1]; // 获取键为1的值

Delete elements:

myMap.erase(1); // 删除键为1的元素

Find elements:

auto it = myMap.find(2); // 查找键为2的元素
if (it != myMap.end()) {
    std::cout << "Found: " << it->second << std::endl;
}

Example

Below is an example usingunordered_mapa simple example, including the output result.

Example

#include <iostream>
#include <unordered_map>

int main() {
    // Create an unordered_map with int keys and string values
    std::unordered_map<int, std::string> myMap;

    // Insert some key-value pairs
    myMap[1] = "one";
    myMap[2] = "two";
    myMap[3] = "three";

    // Print all elements
    for (const auto& pair : myMap) {
        std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl;
    }

    // Access the value of a specific key
    std::cout << "Value for key 2: " << myMap[2] << std::endl;

    // Erase the element with key 1
    myMap.erase(1);

    // Print all elements again
    std::cout << "After erasing key 1:" << std::endl;
    for (const auto& pair : myMap) {
        std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl;
    }

    return 0;
}

Output:

Key: 1, Value: one
Key: 2, Value: two
Key: 3, Value: three
Value for key 2: two
After erasing key 1:
Key: 2, Value: two
Key: 3, Value: three

Notes

  • unordered_mapThe order of elements is not guaranteed, so the iteration order of elements may vary across different runs.
  • The performance of the hash table depends on a good hash function to avoid excessive hash collisions.
  • andstd::mapIn comparison,unordered_mapMay occupy more memory when the number of elements is small.
other extensions