c++关于map的find和count的使用

c++关于map的find和count的使用 http://www.cnblogs.com/Deribs4/p/4948351.html

编程的时候比较常用,今天记录一下,以后备用。

使用count,返回的是被查找元素的个数。如果有,返回1;否则,返回0。注意,map中不存在相同元素,所以返回值只能是1或0。

使用find,返回的是被查找元素的位置,没有则返回map.end()。

例子:

复制代码
 1 #include<string>
 2 #include<cstring>
 3 #include<iostream>
 4 #include<queue>
 5 #include<map>
 6 #include<algorithm>
 7 using namespace std;
 8 int main(){
 9     map<string,int> test;
10     test.insert(make_pair("test1",1));//test["test1"]=1
11     test.insert(make_pair("test2",2));//test["test2"]=2
12     map<string,int>::iterator it;
13     it=test.find("test0");
14     cout<<"test0 find:";
15     if(it==test.end()){
16         cout<<"test0 not found"<<endl;
17     }
18     else{
19         cout<<it->second<<endl;
20     }
21     cout<<"test0 count:";
22     cout<<test.count("test1")<<endl;
23 
24     cout<<"test1 find:";
25     it=test.find("test1");
26     if(it==test.end()){
27         cout<<"test1 not found"<<endl;
28     }
29     else{
30         cout<<it->second<<endl;
31     }
32     cout<<"test1 count:";
33     cout<<test.count("test1")<<endl;
34 
35     cout<<"after inserting test1"<<endl;
36     test.insert(make_pair("test1",2));
37     cout<<"test1 find:";
38     it=test.find("test1");
39     if(it==test.end()){
40         cout<<"test1 not found"<<endl;
41     }
42     else{
43         cout<<it->second<<endl;
44     }
45     cout<<"test1 count:";
46     cout<<test.count("test1")<<endl;
47     return 0;
48 }
复制代码

 

运行结果:

标签: c++, map
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值