• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
Niro Einteson
文可提笔安天下 武可上马定乾坤
博客园    首页    新随笔    联系   管理    订阅  订阅

map遍历

map遍历

 

测试代码:

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 void show(map<int,string>& mp)
 4 {
 5     map<int,string>::iterator iter=mp.begin();
 6     while(iter!=mp.end())
 7     {
 8         cout<<iter->first<<" "<<iter->second<<endl;
 9         iter++;
10     }
11     cout<<endl;
12 }
13 int main()
14 {
15     //构造 map
16     map<int,string> mp;
17     mp.insert({5,"map 5"});//使用{}
18     mp.insert({6,"map 6"});//使用{}
19     mp.insert({7,"map 7"});//使用{}
20     mp.insert({8,"map 8"});//使用{}
21     mp.insert({0,"map 0"});//使用{}
22     mp.insert({1,"map 1"});//使用{}
23     mp.insert({2,"map 2"});//使用{}
24     mp.insert({3,"map 3"});//使用{}
25     mp.insert({4,"map 4"});//使用{}
26 
27 
28     //map的遍历
29     for(auto& it:mp) //auto自动识别为迭代器类型
30     {
31         // cout<<it->second<<endl;
32         cout<<it.second<<endl;
33     }
34     cout<<endl;
35     //正向迭代器:
36     map<int,string>::iterator iter=mp.begin();
37     while(iter != mp.end())
38     {
39         cout<< " first "<< iter->first << " second "<<iter->second<<std::endl;
40         iter++;
41     }
42     cout<<endl;
43     for(iter=mp.begin();iter!=mp.end();iter++){
44         cout<< " first "<< iter->first << " second "<<iter->second<<std::endl;
45     }
46     cout<<endl;
47 
48     //反向迭代器:
49     map<int,string>::reverse_iterator itera=mp.rbegin();
50     while(itera != mp.rend())
51     {
52         cout<< " first "<< itera->first << " second "<<itera->second<<std::endl;
53         itera++;
54     }
55     return 0;
56 }

运行结果:

 1 map 0
 2 map 1
 3 map 2
 4 map 3
 5 map 4
 6 map 5
 7 map 6
 8 map 7
 9 map 8
10 
11  first 0 second map 0
12  first 1 second map 1
13  first 2 second map 2
14  first 3 second map 3
15  first 4 second map 4
16  first 5 second map 5
17  first 6 second map 6
18  first 7 second map 7
19  first 8 second map 8
20 
21  first 0 second map 0
22  first 1 second map 1
23  first 2 second map 2
24  first 3 second map 3
25  first 4 second map 4
26  first 5 second map 5
27  first 6 second map 6
28  first 7 second map 7
29  first 8 second map 8
30 
31  first 8 second map 8
32  first 7 second map 7
33  first 6 second map 6
34  first 5 second map 5
35  first 4 second map 4
36  first 3 second map 3
37  first 2 second map 2
38  first 1 second map 1
39  first 0 second map 0

 

 

 

 

 

posted @ 2019-12-01 20:52  Nirogo  阅读(160)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3