C++ HashMap: Implementation with unordered_map

While C++ does not have a built-in hashmap data structure, you can implement a hash map using the unordered_map in the STL. The unordered_map provides the functionality of a hash table, allowing you to store key-value pairs and quickly search for a value based on its key.

Here is a basic usage example of unordered_map:

#include <iostream>
#include <unordered_map>

int main() {
    std::unordered_map<std::string, int> myMap;

    // 插入元素
    myMap["apple"] = 5;
    myMap["banana"] = 3;
    
    // 查找元素
    std::cout << "apple = " << myMap["apple"] << std::endl;
    
    // 遍历元素
    for (auto& pair : myMap) {
        std::cout << pair.first << " = " << pair.second << std::endl;
    }

    return 0;
}

In the above example, an unordered_map object called myMap is first created, and then two key-value pairs are inserted. The elements can easily be inserted and accessed by using the square bracket operator[]. Iterating through the unordered_map can be done using a range-based for loop, allowing access to and outputting each key-value pair.

bannerAds