C++ STL 中 map 容器

C++ STL 中 map 容器html

Map是STL的一個關聯容器,它提供一對一(其中第一個能夠稱爲關鍵字,每一個關鍵字只能在map中出現一次,第二個可能稱爲該關鍵字的值)的數據 處理能力,因爲這個特性,它完成有可能在咱們處理一對一數據的時候,在編程上提供快速通道。這裏說下map內部數據的組織,map內部自建一顆紅黑樹(一 種非嚴格意義上的平衡二叉樹),這顆樹具備對數據自動排序的功能,因此在map內部全部的數據都是有序的,後邊咱們會見識到有序的好處。ios

  

一、map簡介算法

map是一類關聯式容器。它的特色是增長和刪除節點對迭代器的影響很小,除了那個操做節點,對其餘的節點都沒有什麼影響。編程

對於迭代器來講,能夠修改實值,而不能修改key。數組

 

二、map的功能app

自動創建Key - value的對應。key 和 value能夠是任意你須要的類型。less

根據key值快速查找記錄,查找的複雜度基本是Log(N),若是有1000個記錄,最多查找10次,1,000,000個記錄,最多查找20次。函數

快速插入Key -Value 記錄。學習

快速刪除記錄url

根據Key 修改value記錄。

遍歷全部記錄。

 

三、使用map

使用map得包含map類所在的頭文件

#include <map> //注意,STL頭文件沒有擴展名.h

map對象是模板類,須要關鍵字和存儲對象兩個模板參數:

std:map<int,string> personnel;

這樣就定義了一個用int做爲索引,並擁有相關聯的指向string的指針.

爲了使用方便,能夠對模板類進行一下類型定義,

typedef map<int,CString> UDT_MAP_INT_CSTRING; UDT_MAP_INT_CSTRING enumMap;

 

四、map的構造函數

 

map共提供了6個構造函數,這塊涉及到內存分配器這些東西,略過不表,在下面咱們將接觸到一些map的構造方法,這裏要說下的就是,咱們一般用以下方法構造一個map:

map<int, string> mapStudent;

 

 

五、數據的插入

 

在構造map容器後,咱們就能夠往裏面插入數據了。這裏講三種插入數據的方法:

 

第一種:用insert函數插入pair數據(C++學習之Pair),下面舉例說明(如下代碼雖然是隨手寫的,應該能夠在VC和GCC下編譯經過,你們能夠運行下看什麼效果,在VC下請加入這條語句,屏蔽4786警告 #pragma warning (disable:4786) )

 1 //數據的插入--第一種:用insert函數插入pair數據  2 #include <map>  3 #include <string>  4 #include <iostream>  5 using namespace std;  6 int main()  7 {  8 map<int, string> mapStudent;  9 mapStudent.insert(pair<int, string>(1, "student_one")); 10 mapStudent.insert(pair<int, string>(2, "student_two")); 11 mapStudent.insert(pair<int, string>(3, "student_three")); 12 map<int, string>::iterator iter; 13 for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++) 14 cout<<iter->first<<' '<<iter->second<<endl; 15 return 0; 16 }

 

第二種:用insert函數插入value_type數據

每一個STL中的類都有value_type這種東西,通俗的說value_type 就是stl容器盛裝的數據的數據類型,例如:

vector<int> vec; vector<int>::value_type x;

上述兩句代碼,第一句是聲明一個盛裝數據類型是int的數據的vector,第二句是使用vector<int>::value_type定義一個變量x,這個變量x其實是int類型的,由於vector<int>::value_type中聲明的爲int型。

相應的,假設有:

vector<C> vec; //假設C是自定義類型  vector<C>::value_type x;

那麼第二句定義的變量x的數據類型是C。

 

每一個STL容器類(感受應該是迭代器類更加準確),都有一句相同的代碼:

typede T value_type;

其中T則是類模板中使用的參數 :

template <class T> 

以STL的list容器爲例,那麼它的類定義就應該有下面的語句:

template<class T> class list{ publict: typedef T value_type; //……  };

 

下面舉例說明:

 1 //第二種:用insert函數插入value_type數據,下面舉例說明   2 #include <map>  3 #include <string>  4 #include <iostream>  5 using namespace std;  6 int main()  7 {  8 map<int, string> mapStudent;  9 mapStudent.insert(map<int, string>::value_type (1, "student_one")); 10 mapStudent.insert(map<int, string>::value_type (2, "student_two")); 11 mapStudent.insert(map<int, string>::value_type (3, "student_three")); 12 map<int, string>::iterator iter; 13 for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++) 14 cout<<iter->first<<' '<<iter->second<<endl; 15 return 0; 16 } 

 

第三種:用數組方式插入數據,下面舉例說明

 1 //第三種:用數組方式插入數據,下面舉例說明   2 #include <map>  3 #include <string>  4 #include <iostream>  5 using namespace std;  6 int main()  7 {  8 map<int, string> mapStudent;  9 mapStudent[1] = "student_one"; 10 mapStudent[2] = "student_two"; 11 mapStudent[3] = "student_three"; 12 map<int, string>::iterator iter; 13 for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++) 14 cout<<iter->first<<' '<<iter->second<<endl; 15 } 

  以上三種用法,雖然均可以實現數據的插入,可是它們是有區別的,固然了第一種和第二種在效果上是完成同樣的,用insert函數插入數據,在數據的 插入上涉及到集合的惟一性這個概念,即當map中有這個關鍵字時,insert操做是插入數據不了的,可是用數組方式就不一樣了,它能夠覆蓋之前該關鍵字對 應的值,用程序說明

mapStudent.insert(map<int, string>::value_type (1, "student_one")); mapStudent.insert(map<int, string>::value_type (1, "student_two"));

上面這兩條語句執行後,map中1這個關鍵字對應的值是「student_one」,第二條語句並無生效,那麼這就涉及到咱們怎麼知道insert語句是否插入成功的問題了,能夠用pair來得到是否插入成功,程序以下

pair<map<int, string>::iterator, bool> Insert_Pair; Insert_Pair = mapStudent.insert(map<int, string>::value_type (1, "student_one"));

咱們經過pair的第二個變量來知道是否插入成功,它的第一個變量返回的是一個map的迭代器,若是插入成功的話Insert_Pair.second應該是true的,不然爲false。

 

六、 map的大小

在往map裏面插入了數據,咱們怎麼知道當前已經插入了多少數據呢,能夠用size函數,用法以下:

Int nSize = mapStudent.size();

 

 

七、     數據的遍歷

這裏也提供三種方法,對map進行遍歷

第一種:應用前向迭代器

第二種:應用反相迭代器

第三種,用數組的形式

 

 1 #include<map>
 2 #include<iostream>
 3 #include<string>
 4 using namespace std;  5 int main()  6 {  7     map<int,string> myString;  8     myString.insert(pair<int,string>(1,"xiaoming"));  9     myString.insert(map<int,string>::value_type (2,"xiaohong")); 10     myString[3] = "xiaoli"; 11 
12     cout<<"向前迭代:"<<endl; 13     map<int,string>::iterator iter;//向前迭代
14     for(iter = myString.begin();iter != myString.end();iter++) 15  { 16         cout<<iter->first<<","<<iter->second<<endl; 17  } 18 
19     cout<<"反向迭代器:"<<endl; 20     map<int,string>::reverse_iterator iter2; 21     for(iter2 = myString.rbegin();iter2 != myString.rend();iter2++) 22         cout<<iter2->first<<","<<iter2->second<<endl; 23 
24     cout<<"數組迭代:"<<endl; 25     int Length = myString.size(); 26     for(int i = 1;i <= Length;i++) 27         cout<<i<<","<<myString[i]<<endl; 28     return 0; 29 }

運行結果:

 

八、查找並獲取map中的元素(包括斷定這個關鍵字是否在map中出現)

在這裏咱們將體會,map在數據插入時保證有序的好處。

要斷定一個數據(關鍵字)是否在map中出現的方法比較多,這裏標題雖然是數據的查找,在這裏將穿插着大量的map基本用法。

這裏給出三種數據查找方法

第一種:用count函數來斷定關鍵字是否出現,其缺點是沒法定位數據出現位置,因爲map的特性,一對一的映射關係,就決定了count函數的返回值只有兩個,要麼是0,要麼是1,出現的狀況,固然是返回1了

第二種:用find函數來定位數據出現位置,它返回的一個迭代器,當數據出現時,它返回數據所在位置的迭代器,若是map中沒有要查找的數據,它返回的迭代器等於end函數返回的迭代器。

查找map中是否包含某個關鍵字條目用find()方法,傳入的參數是要查找的key,在這裏須要提到的是begin()和end()兩個成員,

分別表明map對象中第一個條目和最後一個條目,這兩個數據的類型是iterator.

 1 #include <map>
 2 #include <string>
 3 #include <iostream>
 4 using namespace std;  5 int main()  6 {  7     map<int, string> mapStudent;  8     mapStudent.insert(pair<int, string>(1, "student_one"));  9     mapStudent.insert(pair<int, string>(2, "student_two")); 10     mapStudent.insert(pair<int, string>(3, "student_three")); 11     map<int, string>::iterator iter; 12     iter = mapStudent.find(1); 13     if(iter != mapStudent.end()) 14        cout<<"Find, the value is "<<iter->second<<endl; 15     else
16        cout<<"Do not Find"<<endl; 17     return 0; 18 }

經過map對象的方法獲取的iterator數據類型是一個std::pair對象,包括兩個數據 iterator->first和 iterator->second分別表明關鍵字和存儲的數據。

 

第三種:Equal_range

  ForwardIter lower_bound(ForwardIter first, ForwardIter last,const _Tp& val)算法返回一個非遞減序列[first, last)中的第一個大於等於值val的位置。這個函數用來返回要查找關鍵字的下界(是一個迭代器)

  ForwardIter upper_bound(ForwardIter first, ForwardIter last, const _Tp& val)算法返回一個非遞減序列[first, last)中第一個大於val的位置。這個函數用來返回要查找關鍵字的上界(是一個迭代器)

 lower_bound和upper_bound以下圖所示:

例如:map中已經插入了1,2,3,4的話,若是lower_bound(2)的話,返回的2,而upper-bound(2)的話,返回的就是3

Equal_range函數返回一個pair,pair裏面第一個變量是Lower_bound返回的迭代器,pair裏面第二個變量是Upper_bound返回的迭代器,若是這兩個迭代器相等的話,則說明map中不出現這個關鍵字。

 1 #include <map>
 2 #include <string>
 3 #include <iostream>
 4 using namespace std;  5 int main()  6 {  7     map<int, string> mapStudent;  8     mapStudent[1] = "student_one";  9     mapStudent[3] = "student_three"; 10     mapStudent[5] = "student_five"; 11     map<int, string>::iterator iter; 12     iter = mapStudent.lower_bound(1); 13     //返回的是下界1的迭代器
14         cout<<iter->second<<endl; 15     iter = mapStudent.lower_bound(2); 16     //返回的是下界2的迭代器
17         cout<<iter->second<<endl; 18     iter = mapStudent.lower_bound(3); 19     //返回的是下界3的迭代器
20         cout<<iter->second<<endl; 21 
22     iter = mapStudent.upper_bound(0); 23     //返回的是上界0的迭代器
24         cout<<iter->second<<endl; 25     iter = mapStudent.upper_bound(1); 26     //返回的是上界1的迭代器
27         cout<<iter->second<<endl; 28     iter = mapStudent.upper_bound(2); 29     //返回的是上界2的迭代器
30         cout<<iter->second<<endl; 31     iter = mapStudent.upper_bound(3); 32     //返回的是上界3的迭代器
33         cout<<iter->second<<endl; 34 
35     pair<map<int, string>::iterator, map<int, string>::iterator> mappair; 36     mappair = mapStudent.equal_range(2); 37     if(mappair.first == mappair.second) 38         cout<<"Do not Find"<<endl; 39     else
40         cout<<"Find"<<endl; 41     mappair = mapStudent.equal_range(3); 42     if(mappair.first == mappair.second) 43         cout<<"Do not Find"<<endl; 44     else
45         cout<<"Find"<<endl; 46     return 0; 47 }

 運行結果:

 

 

九、從map中刪除元素

移除某個map中某個條目用erase()

該成員方法的定義以下:

iterator erase(iterator it);//經過一個條目對象刪除
 iterator erase(iterator first,iterator last);//刪除一個範圍
 size_type erase(const Key&key);//經過關鍵字刪除
 clear()就至關於enumMap.erase(enumMap.begin(),enumMap.end());

這裏要用到erase函數,它有三個重載了的函數,下面在例子中詳細說明它們的用法

 1 #include <map>
 2 #include <string>
 3 #include <iostream>
 4 using namespace std;  5 int main()  6 {  7        map<int, string> mapStudent;  8        mapStudent.insert(pair<int, string>(1, "student_one"));  9        mapStudent.insert(pair<int, string>(2, "student_two")); 10        mapStudent.insert(pair<int, string>(3, "student_three")); 11        //若是你要演示輸出效果,請選擇如下的一種,你看到的效果會比較好 12        //若是要刪除1,用迭代器刪除
13        map<int, string>::iterator iter; 14        iter = mapStudent.find(1); 15  mapStudent.erase(iter); 16        
17        //若是要刪除1,用關鍵字刪除
18        int n = mapStudent.erase(1);//若是刪除了會返回1,不然返回0 19        
20        //用迭代器,成片的刪除 21        //一下代碼把整個map清空
22  mapStudent.erase( mapStudent.begin(), mapStudent.end() ); 23        //成片刪除要注意的是,也是STL的特性,刪除區間是一個前閉後開的集合 24        //自個加上遍歷代碼,打印輸出吧
25 }

十、map中的swap用法

map中的swap不是一個容器中的元素交換,而是兩個容器全部元素的交換。

 

十一、 排序  map中的sort問題

map中的元素是自動按Key升序排序,因此不能對map用sort函數;

這裏要講的是一點比較高深的用法了,排序問題,STL中默認是採用小於號來排序的,以上代碼在排序上是不存在任何問題的,由於上面的關鍵字是int 型,它自己支持小於號運算,在一些特殊狀況,好比關鍵字是一個結構體,涉及到排序就會出現問題,由於它沒有小於號操做,insert等函數在編譯的時候過 不去,下面給出兩個方法解決這個問題。

 第一種:小於號重載

 1 #include <iostream>
 2 #include <string>
 3 #include <map>
 4 using namespace std;  5 typedef struct tagStudentinfo  6 {  7        int niD;  8        string strName;  9        bool operator < (tagStudentinfo const& _A) const
10        {     //這個函數指定排序策略,按niD排序,若是niD相等的話,按strName排序
11             if(niD < _A.niD) return true; 12             if(niD == _A.niD) 13                 return strName.compare(_A.strName) < 0; 14         return false; 15  } 16 }Studentinfo, *PStudentinfo; //學生信息
17 int main() 18 { 19     int nSize;   //用學生信息映射分數
20     map<Studentinfo, int>mapStudent; 21     map<Studentinfo, int>::iterator iter; 22  Studentinfo studentinfo; 23     studentinfo.niD = 1; 24     studentinfo.strName = "student_one"; 25     mapStudent.insert(pair<Studentinfo, int>(studentinfo, 90)); 26     studentinfo.niD = 2; 27     studentinfo.strName = "student_two"; 28     mapStudent.insert(pair<Studentinfo, int>(studentinfo, 80)); 29     for (iter=mapStudent.begin(); iter!=mapStudent.end(); iter++) 30         cout<<iter->first.niD<<' '<<iter->first.strName<<' '<<iter->second<<endl; 31     return 0; 32 }

第二種:仿函數的應用,這個時候結構體中沒有直接的小於號重載

 1 //第二種:仿函數的應用,這個時候結構體中沒有直接的小於號重載,程序說明
 2 #include <iostream>
 3 #include <map>
 4 #include <string>
 5 using namespace std;  6 typedef struct tagStudentinfo  7 {  8        int niD;  9        string strName; 10 }Studentinfo, *PStudentinfo; //學生信息
11 class sort 12 { 13 public: 14     bool operator() (Studentinfo const &_A, Studentinfo const &_B) const
15  { 16         if(_A.niD < _B.niD) 17             return true; 18         if(_A.niD == _B.niD) 19             return _A.strName.compare(_B.strName) < 0; 20     return false; 21  } 22 }; 23 int main() 24 {   //用學生信息映射分數
25     map<Studentinfo, int, sort>mapStudent; 26     map<Studentinfo, int>::iterator iter; 27  Studentinfo studentinfo; 28     studentinfo.niD = 1; 29     studentinfo.strName = "student_one"; 30     mapStudent.insert(pair<Studentinfo, int>(studentinfo, 90)); 31     studentinfo.niD = 2; 32     studentinfo.strName = "student_two"; 33     mapStudent.insert(pair<Studentinfo, int>(studentinfo, 80)); 34     for (iter=mapStudent.begin(); iter!=mapStudent.end(); iter++) 35         cout<<iter->first.niD<<' '<<iter->first.strName<<' '<<iter->second<<endl; 36     return 0; 37 }

  因爲STL是一個統一的總體,map的不少用法都和STL中其它的東西結合在一塊兒,好比在排序上,這裏默認用的是小於號,即less<>,若是要從大到小排序呢,這裏涉及到的東西不少,在此沒法一一加以說明。

  還要說明的是,map中因爲它內部有序,由紅黑樹保證,所以不少函數執行的時間複雜度都是log2N的,若是用map函數能夠實現的功能,而STL Algorithm也能夠完成該功能,建議用map自帶函數,效率高一些。

  下面說下,map在空間上的特性,不然,估計你用起來會有時候表現的比較鬱悶,因爲map的每一個數據對應紅黑樹上的一個節點,這個節點在不保存你的 數據時,是佔用16個字節的,一個父節點指針,左右孩子指針,還有一個枚舉值(標示紅黑的,至關於平衡二叉樹中的平衡因子),我想你們應該知道,這些地方 很費內存了吧,不說了……

 

十二、 map的基本操做函數:

     C++ maps是一種關聯式容器,包含「關鍵字/值」對

     begin()         返回指向map頭部的迭代器

     clear()        刪除全部元素

     count()         返回指定元素出現的次數

     empty()         若是map爲空則返回true

     end()           返回指向map末尾的迭代器

     equal_range()   返回特殊條目的迭代器對

     erase()         刪除一個元素

     find()          查找一個元素

     get_allocator() 返回map的配置器

     insert()        插入元素

     key_comp()      返回比較元素key的函數

     lower_bound()   返回鍵值>=給定元素的第一個位置

     max_size()      返回能夠容納的最大元素個數

     rbegin()        返回一個指向map尾部的逆向迭代器

     rend()          返回一個指向map頭部的逆向迭代器

     size()          返回map中元素的個數

     swap()           交換兩個map

     upper_bound()    返回鍵值>給定元素的第一個位置

     value_comp()     返回比較元素value的函數

 

本文章由如下博客或文章地址整理而成,目的爲了方便本身和你們的查閱、理解。

http://blog.csdn.net/uqapuqap/archive/2009/08/14/4448067.aspx

http://www.360doc.com/content/13/0912/18/3373961_314006267.shtml#

http://blog.csdn.net/shawn_hou/article/details/38035577###;

相關文章
相關標籤/搜索