C++ unordered_map遍历有哪些方法

   2024-10-05 2580
核心提示:在C++中,可以使用以下方法来遍历unordered_map:使用迭代器遍历:std::unordered_mapint, std::string myMap = {{1, apple}, {2

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

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式 | 网站留言    |  赣ICP备2021007278号