阅读量:0
在C++中,可以使用以下方法来遍历unordered_map:
- 使用迭代器遍历:
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; }
- 使用范围-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; }
- 使用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; });
- 使用范围-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; }