温馨提示×

C++ unordered_map遍历有哪些方法

c++
小樊
190
2024-07-25 00:43:12
栏目: 编程语言

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

0