c++

c++遍历哈希表的方法是什么

小亿
198
2024-02-23 10:13:28
栏目: 编程语言

在C++中,可以使用迭代器来遍历哈希表。以下是一个示例代码:

#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;
}

在上面的示例中,我们使用unordered_map来创建一个哈希表,并使用迭代器it来遍历哈希表。我们可以通过it->firstit->second来访问哈希表中的键和值。

0
看了该问题的人还看了