c++ map备忘

来源:互联网 发布:linux初学者书籍 编辑:程序博客网 时间:2024/05/21 04:25

例子

#include<iostream>#include<map>using namespace std;int main(){    map<string,string> mymap;    mymap["animal1"] = "dog";    mymap["animal2"] = "cat";    mymap["animal3"] = "pig";    auto it = mymap.find("animal2");    if(it != mymap.end()){        cout<<it->first<<" "<<it->second<<endl;  //animal2 cat    }    cout<<mymap.count("animal2")<<endl;  //1    //*********lower_bound(k)************    //returns an iterator to the first element with key not less than k    cout<<"*********lower_bound************"<<endl;    it = mymap.lower_bound("animal2");    if(it != mymap.end()){        cout<<it->first<<" "<<it->second<<endl;  //animal2 cat    }    it = mymap.lower_bound("animal0");    if(it != mymap.end()){        cout<<it->first<<" "<<it->second<<endl;  //animal1 dog    }    it = mymap.lower_bound("animal5");  //it == mymap.end()    if(it != mymap.end()){        cout<<it->first<<" "<<it->second<<endl;    }    //*********upper_bound(k)************    //returns an iterator to the first element with key greater than k    cout<<"*********upper_bound************"<<endl;    it = mymap.upper_bound("animal2");    if(it != mymap.end()){        cout<<it->first<<" "<<it->second<<endl;  //animal3 pig    }    it = mymap.upper_bound("animal0");    if(it != mymap.end()){        cout<<it->first<<" "<<it->second<<endl;  //animal1 dog    }    it = mymap.upper_bound("animal5");  //it == mymap.end()    if(it != mymap.end()){        cout<<it->first<<" "<<it->second<<endl;      }    //*********equal_range(k)************    //returns a pair of iterators denoting the elements with key k    //the first iterator is equal to what the lower_bound return    //the second iterator is equal to what the upper_bound return    cout<<"*********equal_range************"<<endl;    auto it1 = mymap.equal_range("animal2");    if(it1.first!=mymap.end()){        cout<<it1.first->first<<" "<<it1.first->second<<endl;  //animal2 cat        cout<<it1.second->first<<" "<<it1.second->second<<endl;  //animal3 pig    }    it1 = mymap.equal_range("animal0");    if(it1.first != mymap.end()){        cout<<it1.first->first<<" "<<it1.first->second<<endl;  //animal1 dog        cout<<it1.second->first<<" "<<it1.second->second<<endl;  //animal1 dog    }    it1 = mymap.equal_range("animal5");  //it1.first == mymap.end() and it1.second == mymap.end()    if(it1.first != mymap.end()){        cout<<it1.first->first<<" "<<it1.first->second<<endl;          cout<<it1.second->first<<" "<<it1.second->second<<endl;    }    return 0;}

结果

animal2 cat
1
****lower_bound*******
animal2 cat
animal1 dog
****upper_bound*******
animal3 pig
animal1 dog
****equal_range*******
animal2 cat
animal3 pig
animal1 dog
animal1 dog

0 0
原创粉丝点击