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

c++
1127
2024/2/15 10:13:28
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在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来访问哈希表中的键和值。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: c++中string拼接字符串的方法是什么