首页 > 编程知识 正文

C stdmap正向遍历与反向遍历的几种方式

时间:2023-05-06 20:07:56 阅读:286723 作者:2408

文章目录 1 std::map正向遍历1.1 for循环1.2 while循环 2 std::map反向遍历2.1 for循环2.2 while循环

1 std::map正向遍历 1.1 for循环 #include <iostream>#include <string>#include <map>int main(){std::map<int, std::string> t_Map;t_Map[0] = "A";t_Map[1] = "B";t_Map[2] = "C";std::map<int, std::string>::iterator iter1;for (iter1 = t_Map.begin();iter1 != t_Map.end();iter1++){std::cout << iter1->first << " : " << iter1->second << std::endl;}getchar();return 0;} 1.2 while循环 #include <iostream>#include <string>#include <map>int main(){std::map<int, std::string> t_Map;t_Map[0] = "A";t_Map[1] = "B";t_Map[2] = "C";std::map<int, std::string>::iterator iter2 = t_Map.begin();while (iter2 != t_Map.end()){std::cout << iter2->first << " : " << iter2->second << std::endl;iter2++;}getchar();return 0;} 2 std::map反向遍历 2.1 for循环 #include <iostream>#include <string>#include <map>int main(){std::map<int, std::string> t_Map;t_Map[0] = "A";t_Map[1] = "B";t_Map[2] = "C";std::map<int, std::string>::reverse_iterator iter1;for (iter1 = t_Map.rbegin();iter1 != t_Map.rend();iter1++){std::cout << iter1->first << " : " << iter1->second << std::endl;}getchar();return 0;} 2.2 while循环 #include <iostream>#include <string>#include <map>int main(){std::map<int, std::string> t_Map;t_Map[0] = "A";t_Map[1] = "B";t_Map[2] = "C";std::map<int, std::string>::reverse_iterator iter2 = t_Map.rbegin();while (iter2 != t_Map.rend()){std::cout << iter2->first << " : " << iter2->second << std::endl;iter2++;}getchar();return 0;}

如果有兴趣可以访问我的个人站:https://www.stubbornhuang.com

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。