温馨提示×

如何高效地遍历C++ unordered_map

c++
小樊
108
2024-07-25 00:44:15
栏目: 编程语言
C++开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在遍历C++ unordered_map时,可以使用迭代器来实现高效遍历。以下是一种常用的方法:

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

在这个例子中,我们使用迭代器it来遍历unordered_mapmyMap。通过it->firstit->second可以访问键和值。这种方法避免了使用at()[]方法,因为这些方法会导致unordered_map的重新哈希,降低遍历效率。

除了使用迭代器,C++11引入了范围for循环,也可以用来遍历unordered_map:

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

这种方法更加简洁明了,但在某些情况下可能会影响性能。因此,根据实际情况选择合适的遍历方法来高效地遍历C++ unordered_map。

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

推荐阅读:C++ unordered_map遍历有哪些方法

0