温馨提示×

C++ unordered_map遍历有哪些方法

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

在C++中,可以使用以下方法来遍历unordered_map:

  1. 使用迭代器遍历:
std::unordered_map<int, std::string> myMap = {{1, "apple"}, {2, "banana"}, {3, "orange"}};
for(auto it = myMap.begin(); it != myMap.end(); ++it) {
    std::cout << "Key: " << it->first << ", Value: " << it->second << std::endl;
}
  1. 使用范围-based for 循环遍历:
std::unordered_map<int, std::string> myMap = {{1, "apple"}, {2, "banana"}, {3, "orange"}};
for(const auto& pair : myMap) {
    std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl;
}
  1. 使用for_each遍历:
std::unordered_map<int, std::string> myMap = {{1, "apple"}, {2, "banana"}, {3, "orange"}};
std::for_each(myMap.begin(), myMap.end(), [](const std::pair<int, std::string>& pair) {
    std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl;
});
  1. 使用范围-based for 循环遍历键或值:
std::unordered_map<int, std::string> myMap = {{1, "apple"}, {2, "banana"}, {3, "orange"}};
for(const auto& pair : myMap) {
    std::cout << "Key: " << pair.first << std::endl;
}

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

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

推荐阅读:如何高效地遍历C++ unordered_map

0