C++ unordered_map遍历有哪些方法

avatar
作者
筋斗云
阅读量: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; } 

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!