map的使用

上例子:

 1 #include <iostream>
 2 #include <cstdio>
 3  
 4 #include <map> //使用什么容器需要提前申明它 
 5 using namespace std;
 6 
 7 map<string, string>Map; 
 8 
 9 int main() 
10 {
11     Map["kitty"] = "中国人"; //类似于索引以及value,赋值 
12      
13     cout << Map["kitty"] << endl; //输出类似于普通数组 
14     
15     Map.erase("kitty");//删除 
16     
17 
18     return 0; 
19 } 

其中,map定义时前面一个为键,后面一个为值。

当然使用时需要迭代器

再看另一个例子(使用迭代器):

 1 #include <string> 
 2 #include <stdio.h>
 3 #include <iostream>
 4 #include <map>
 5 
 6 using namespace std;
 7 
 8 int main()
 9 {
10     int n;
11     string ballon;
12     while(cin >> n,n)//逗号表达式,当输入为0时退出循环,不为0时进入循环 
13     {
14         map<string,int> m;//创建映射m 
15         int N=n;
16         while(N--)
17         {
18             cin >> ballon;//输入气球的颜色 
19             ++m[ballon];//相应气球颜色的数目加1 。即初始值为0 
20         }
21         map<string,int>::iterator p;//map函数还是需要迭代器输出 
22         int maxx=0;
23         string max_ballon;
24         
25         for(p=m.begin();p!=m.end();++p)
26         {
27             if(p->second>maxx)
28             {
29                 maxx=p->second;
30                 max_ballon=p->first;
31             }
32         }
33         cout << max_ballon <<endl;
34     }
35     return 0;
36 }
View Code

first表示map里面的键,second表示map里面的值。

posted @ 2018-09-08 17:27  achived  阅读(180)  评论(0编辑  收藏  举报