1. 程式人生 > >C++ map中find與count的使用

C++ map中find與count的使用

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

使用find,返回的是被查詢元素的位置,沒有則返回map.end()。

例子:

1 #include
2 #include
3 #include
4 #include
5 #include
6 #include
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(ittest.end()){
16 cout<<“test0 not found”<<endl;
17 }
18 else{
19 cout<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<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<second<<endl;
44 }
45 cout<<“test1 count:”;
46 cout<<test.count(“test1”)<<endl;
47 return 0;
48 }