1 map和set两种容器的底层结构都是红黑树,所以容器中不会出现相同的元素,
2 因此count()的结果只能为0和1,可以以此来判断键值元素是否存在
3 (当然也可以使用find()方法判断键值是否存在)。
4 拿map<key,value>举例,find()方法返回值是一个迭代器,
5 成功返回迭代器指向要查找的元素,失败返回的迭代器指向end。
6 count()方法返回值是一个整数,1表示有这个元素,0表示没有这个元素。
7 #include<iostream>
8 #include<map>
9 #include<string>
10 using namespace std;
11
12 int main()
13 {
14 map<int,string>maps;
15 map<int,string>::iterator it;
16 if(maps.find(1)==maps.end())//返回迭代器。
17 {
18 cout<<"没有1这个元素"<<endl;
19 }
20 if(maps.count(1)==0)//只返回1或0。
21 {
22 cout<<"没有1这个元素"<<endl;
23 }
24 //添加元素1
25 maps[1]="one";
26
27 if(maps.find(1)!=maps.end())
28 {
29 it=maps.find(1);
30 cout<<it->second<<endl;
31 //cout<<"有1这个元素"<<endl;
32 }
33 if(maps.count(1))
34 {
35 cout<<"有1这个元素"<<endl;
36 }
37 return 0;
38 }
1 while(~scanf("%d%d%d",&id,&h,&m)){
2 P p = mp[id];
3 mp[id].first = h,mp[id].second = m;
4 printf("%d %d\n",h,m);
5 printf("%d %d\n",p.first,p.second);
6 printf("%d %d\n",mp[id].first,mp[id].second);
7 }
8 1 5 2
9 5 2
10 0 0
11 5 2
12 return 0;
13 }