小男孩‘自慰网亚洲一区二区,亚洲一级在线播放毛片,亚洲中文字幕av每天更新,黄aⅴ永久免费无码,91成人午夜在线精品,色网站免费在线观看,亚洲欧洲wwwww在线观看

分享

c++中map的嵌套用法

 禁忌石 2017-04-20
c++中map的基本用法和嵌套用法
2013-09-30      0 個(gè)評(píng)論      
收藏    我要投稿
C++中map容器提供一個(gè)鍵值對(duì)容器,map與multimap差別僅僅在于multiple允許一個(gè)鍵對(duì)應(yīng)多個(gè)值。本文主要總結(jié)一下map基本用法和嵌套用法示例。
 
一、map基本用法
  1   頭文件 
  #include   <map> 
 
 
 
  2   定義 
  map<int,   int>   my_Map; //注意這里的int和int可以是其他類型
  或者是typedef     map<int,   int>   MY_MAP; 
  MY_MAP   my_Map; 
 
 
 
  3   插入數(shù)據(jù) 
  (1)   my_Map[1]   =   1; 
  (2)   my_Map.insert(map<int, int>::value_type(2,2)); 
  (3)   my_Map.insert(pair<int,int>(3,3)); 
  (4)   my_Map.insert(make_pair<string,int>(4,4)); 
  
  4   查找數(shù)據(jù)和修改數(shù)據(jù) 
  (1)   int   i   =   my_Map[1]; 
            my_Map[1]   =   i; 
  (2)   MY_MAP::iterator   my_Itr; 
            my_Itr.find(2); 
            int   j   =   my_Itr->second; 
            my_Itr->second   =   j; 
注意:
 
A.鍵本身是不能被修改的,除非刪除。 
 
B.不管鍵存不存在,比如my_Map[1]   =   i;,都會(huì)執(zhí)行賦值操作。
  
  5   刪除數(shù)據(jù) 
  (1)   my_Map.erase(my_Itr); 
  (2)   my_Map.erase(3); 
 
  
  6   遍歷數(shù)據(jù) 
  for   (my_Itr=my_Map.begin();   my_Itr!=my_Map.end();   ++my_Itr)   {} 
  
  7   其它方法 
  my_Map.size() :返回元素?cái)?shù)目 
  my_Map.empty():判斷是否為空 
  my_Map.clear() :清空所有元素 
 
 
二、嵌套用法
 
1.示例如下:
 
 
[cpp] 
map<int,map<int,int> >multiMap; //對(duì)于這樣的map嵌套定義,    
map<int, int> temp;    //定義一個(gè)map<int, string>變量,對(duì)其定義后在插入multiMap    
temp[9] = 9;    
temp[10] = 10;    
multiMap[10] = temp;    
multiMap[10][11]=11;     
multiMap[5][30]=30;    
map<int,map<int,int> >::iterator multitr;  // 以下是如何遍歷本multiMap    
map<int,int>::iterator intertr;    
for(multitr=multiMap.begin();multitr!=multiMap.end();multitr++)    
{   
    for(intertr= multitr ->second.begin(); intertr != multitr ->second.end(); intertr ++)    
        cout<< multitr ->first<<" "<<intertr->first<<" ("<<intertr -> second <<")"<<endl;    
}   
 
2.
 
也可以這樣:
 
[cpp] 
map<int,map<int,int>* >multiMap;  
map<int, int>* temp = new map<int, int>;  
multiMap[10]=temp;  
 
這樣動(dòng)態(tài)new內(nèi)存,就要記得delete,否則會(huì)有內(nèi)存泄露,delete如下:
 
[cpp]  
map<int, int>* temp1;  
for(multitr=multiMap.begin();multitr!=multiMap.end();multitr++)    
{   
    temp1 = multitr ->second;  
        delete  temp1;  
        temp1 = NULL;  
}   

    本站是提供個(gè)人知識(shí)管理的網(wǎng)絡(luò)存儲(chǔ)空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請(qǐng)注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購(gòu)買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊一鍵舉報(bào)。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評(píng)論

    發(fā)表

    請(qǐng)遵守用戶 評(píng)論公約

    類似文章 更多