What is the method to traverse a hash table in C++?

In C++, iterators can be used to traverse a hash table. Here is an example code:

#include <iostream>
#include <unordered_map>

int main() {
    std::unordered_map<int, std::string> myMap = {
        {1, "One"},
        {2, "Two"},
        {3, "Three"}
    };

    // 遍历哈希表
    for (auto it = myMap.begin(); it != myMap.end(); ++it) {
        std::cout << "Key: " << it->first << ", Value: " << it->second << std::endl;
    }

    return 0;
}

In the example above, we used an unordered_map to create a hash table and used the iterator it to traverse the hash table. We can access the keys and values in the hash table using it->first and it->second.

bannerAds