c++關於map的find和count的使用

謝謝原博對我學習上的幫助,原文地址:https://www.cnblogs.com/Deribs4/p/4948351.html


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

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


#include<string>
#include<cstring>
#include<iostream>
#include<queue>
#include<map>
#include<algorithm>
using namespace std;
int main(){
    map<string,int> test;
    test.insert(make_pair("test1",1));//test["test1"]=1
    test.insert(make_pair("test2",2));//test["test2"]=2
    map<string,int>::iterator it;
    it=test.find("test0");
    cout<<"test0 find:";
    if(it==test.end()){
        cout<<"test0 not found"<<endl;
    }
    else{
        cout<<it->second<<endl;
    }
    cout<<"test0 count:";
    cout<<test.count("test1")<<endl;

    cout<<"test1 find:";
    it=test.find("test1");
    if(it==test.end()){
        cout<<"test1 not found"<<endl;
    }
    else{
        cout<<it->second<<endl;
    }
    cout<<"test1 count:";
    cout<<test.count("test1")<<endl;

    cout<<"after inserting test1"<<endl;
    test.insert(make_pair("test1",2));
    cout<<"test1 find:";
    it=test.find("test1");
    if(it==test.end()){
        cout<<"test1 not found"<<endl;
    }
    else{
        cout<<it->second<<endl;
    }
    cout<<"test1 count:";
    cout<<test.count("test1")<<endl;
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章