STL之map

  1 ```
  2 #include<iostream>
  3 #include<algorithm>
  4 #include<map>
  5 #include<cstring>
  6 #include<cstdlib>
  7 using namespace std;
  8 
  9 
 10 //初始化
 11 void test01(){
 12     map<int,int> mymap;
 13     //四种方式插入数据
 14     /*insert插入返回的是一个对组,第一个值为一个迭代器,第二个之为一个bool*/
 15     pair< map<int,int>::iterator, bool > ret=mymap.insert(pair<int,int>(10,10));
 16     if(ret.second){
 17         cout<<"第一次插入成功!"<<endl;
 18     }
 19     else{
 20         cout<<"插入失败"<<endl;
 21     }
 22     ret=mymap.insert(pair<int,int>(10,20));
 23     if(ret.second){
 24         cout<<"第二次插入成功"<<endl;
 25     }
 26     else{
 27         cout<<"插入失败"<<endl;
 28     }
 29 
 30     mymap.insert(make_pair(20,20));
 31     mymap.insert(map<int,int>::value_type(30,30));
 32     mymap[40]=40;
 33     mymap[10]=20;
 34     mymap[50]=50;
 35     /*如果key不存在,创建pair加入到map容器中
 36       如果发现key存在,那么会修改key对应的value*/
 37 
 38     //打印
 39     for(map<int,int>::iterator it =mymap.begin();it!=mymap.end(); it++ ){
 40         cout<<"key:"<<it->first<<" value:"<<(*it).second<<endl;
 41     }
 42     /*如果通过[]中括号的方式去访问map中不存在的key
 43       那么map会将这个访问的key插入到map中,并且给value一个默认值*/
 44     cout<<"mymap[60]:"<<mymap[60]<<endl;
 45     //打印
 46     for(map<int,int>::iterator it =mymap.begin();it!=mymap.end(); it++ ){
 47         cout<<"key:"<<it->first<<" value:"<<(*it).second<<endl;
 48     }
 49 
 50 }
 51 
 52 class MyKey{
 53 public:
 54     int mIndex;
 55     int mID;
 56 public:
 57     MyKey(int index,int id):mIndex(index),mID(id){}
 58 };
 59 
 60 struct mycompare{
 61     bool operator()(MyKey key1,MyKey key2){
 62         return key1.mIndex>key2.mIndex;
 63     }
 64 };
 65 //class mycompare{
 66 //public:
 67 //    bool operator()(MyKey key1,MyKey key2){
 68 //        return key1.mIndex>key2.mIndex;
 69 //    }
 70 //};
 71 
 72 void test02(){
 73     map<MyKey,int,mycompare> mymap;
 74     mymap.insert(make_pair(MyKey(1,2),10));
 75     mymap.insert(make_pair(MyKey(4,5),20));
 76 
 77     for(map<MyKey,int,mycompare>::iterator it=mymap.begin(); it!=mymap.end(); it++ ){
 78         cout<<it->first.mIndex<<":"<<it->first.mID<<"="<<it->second<<endl;
 79     }
 80 }
 81 
 82 void test03(){
 83     map<int,int> mymap;
 84     mymap.insert(make_pair(1,4));
 85     mymap.insert(make_pair(2,5));
 86     mymap.insert(make_pair(3,6));
 87 
 88     pair<map<int,int>::iterator,map<int,int>::iterator> ret=mymap.equal_range(2);
 89     if(ret.first->second){
 90         cout<<"找到lower_bound!"<<endl;
 91     }
 92     else{
 93         cout<<"没有找到"<<endl;
 94     }
 95     if(ret.second->second){
 96         cout<<"找到upper_bound!"<<endl;
 97     }
 98     else{
 99         cout<<"没有找到"<<endl;
100     }
101 }
102 
103 int main(){
104 
105     test03();
106 
107 
108     return 0;
109 }
110 
111 ```

猜你喜欢

转载自www.cnblogs.com/Bravewtz/p/10325819.html