1. 程式人生 > >STL之map

STL之map

algo make 如果 operator str key lower iostream insert

  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 ```

STL之map