1. 程式人生 > >C++中的STL中map用法詳解

C++中的STL中map用法詳解

Map是STL的一個關聯容器,它提供一對一(其中第一個可以稱為關鍵字,每個關鍵字只能在map中出現一次,第二個可能稱為該關鍵字的值)的資料 處理能力,由於這個特性,它完成有可能在我們處理一對一資料的時候,在程式設計上提供快速通道。這裡說下map內部資料的組織,map內部自建一顆紅黑樹(一 種非嚴格意義上的平衡二叉樹),這顆樹具有對資料自動排序的功能,所以在map內部所有的資料都是有序的,後邊我們會見識到有序的好處。

1、map簡介

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

對於迭代器來說,可以修改實值,而不能修改key。

2、map的功能

自動建立Key - value的對應。key 和 value可以是任意你需要的型別。

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

快速插入Key -Value 記錄。

快速刪除記錄

根據Key 修改value記錄。

遍歷所有記錄。

3、使用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;

4、       map的建構函式

map共提供了6個建構函式,這塊涉及到記憶體分配器這些東西,略過不表,在下面我們將接觸到一些map的構造方法,這裡要說下的就是,我們通常用如下方法構造一個map:

map<int, string> mapStudent;

5、     資料的插入

在構造map容器後,我們就可以往裡面插入資料了。這裡講三種插入資料的方法:

第一種:用insert函式插入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. }  

第二種:用insert函式插入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. }  


第三種:用陣列方式插入資料,下面舉例說明

  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。

下面給出完成程式碼,演示插入成功與否問題

  1. //驗證插入函式的作用效果  
  2. #include <map>  
  3. #include <string>  
  4. #include <iostream>  
  5. using namespace std;  
  6. int main()  
  7. {  
  8.     map<int, string> mapStudent;  
  9.     pair<map<int, string>::iterator, bool> Insert_Pair;  
  10.     Insert_Pair = mapStudent.insert(pair<int, string>(1, "student_one"));  
  11.     if(Insert_Pair.second == true)  
  12.         cout<<"Insert Successfully"<<endl;  
  13.     else  
  14.         cout<<"Insert Failure"<<endl;  
  15.     Insert_Pair = mapStudent.insert(pair<int, string>(1, "student_two"));  
  16.     if(Insert_Pair.second == true)  
  17.         cout<<"Insert Successfully"<<endl;  
  18.     else  
  19.         cout<<"Insert Failure"<<endl;  
  20.     map<int, string>::iterator iter;  
  21.     for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++)  
  22.        cout<<iter->first<<' '<<iter->second<<endl;  
  23. }  


大家可以用如下程式,看下用陣列插入在資料覆蓋上的效果

  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[1] = "student_two";  
  11.     mapStudent[2] = "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. }  

6、      map的大小

在往map裡面插入了資料,我們怎麼知道當前已經插入了多少資料呢,可以用size函式,用法如下:

Int nSize = mapStudent.size();

7、     資料的遍歷

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

第一種:應用前向迭代器,上面舉例程式中到處都是了,略過不表

第二種:應用反相迭代器,下面舉例說明,要體會效果,請自個動手執行程式

  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.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>::reverse_iterator iter;  
  13.     for(iter = mapStudent.rbegin(); iter != mapStudent.rend(); iter++)  
  14.         cout<<iter->first<<"  "<<iter->second<<endl;  
  15. }  

第三種,用陣列的形式,程式說明如下:

  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.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.     int nSize = mapStudent.size();  
  13. //此處應注意,應該是 for(int nindex = 1; nindex <= nSize; nindex++)  
  14. //而不是 for(int nindex = 0; nindex < nSize; nindex++)  
  15.     for(int nindex = 1; nindex <= nSize; nindex++)  
  16.         cout<<mapStudent[nindex]<<endl;  
  17. }  

8、    查詢並獲取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分別代表關鍵字和儲存的資料。

第三種:這個方法用來判定資料是否出現,是顯得笨了點,但是,我打算在這裡講解

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.     //返回的是下界3的迭代器  
  17.         cout<<iter->second<<endl;  
  18.     iter = mapStudent.lower_bound(3);  
  19.     //返回的是下界3的迭代器  
  20.         cout<<iter->second<<endl;  
  21.     iter = mapStudent.upper_bound(2);  
  22.     //返回的是上界3的迭代器  
  23.         cout<<iter->second<<endl;  
  24.     iter = mapStudent.upper_bound(3);  
  25.     //返回的是上界5的迭代器  
  26.         cout<<iter->second<<endl;  
  27.     pair<map<int, string>::iterator, map<int, string>::iterator> mappair;  
  28.     mappair = mapStudent.equal_range(2);  
  29.     if(mappair.first == mappair.second)  
  30.         cout<<"Do not Find"<<endl;  
  31.     else  
  32.         cout<<"Find"<<endl;  
  33.     mappair = mapStudent.equal_range(3);  
  34.     if(mappair.first == mappair.second)  
  35.         cout<<"Do not Find"<<endl;  
  36.     else  
  37.         cout<<"Find"<<endl;  
  38.     return 0;  
  39. }  


9、    從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.        //如果要刪除1,用關鍵字刪除  
  17.        int n = mapStudent.erase(1);//如果刪除了會返回1,否則返回0  
  18.        //用迭代器,成片的刪除  
  19.        //一下程式碼把整個map清空  
  20.        mapStudent.erase( mapStudent.begin(), mapStudent.end() );  
  21.        //成片刪除要注意的是,也是STL的特性,刪除區間是一個前閉後開的集合  
  22.        //自個加上遍歷程式碼,列印輸出吧  
  23. }  


10、    map中的swap用法

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

11、     排序 ·  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. }  

由於STL是一個統一的整體,map的很多用法都和STL中其它的東西結合在一起,比如在排序上,這裡預設用的是小於號,即less<>,如果要從大到小排序呢,這裡涉及到的東西很多,在此無法一一加以說明。

還要說明的是,map中由於它內部有序,由紅黑樹保證,因此很多函式執行的時間複雜度都是log2N的,如果用map函式可以實現的功能,而STL Algorithm也可以完成該功能,建議用map自帶函式,效率高一些。

下面說下,map在空間上的特性,否則,估計你用起來會有時候表現的比較鬱悶,由於map的每個資料對應紅黑樹上的一個節點,這個節點在不儲存你的 資料時,是佔用16個位元組的,一個父節點指標,左右孩子指標,還有一個列舉值(標示紅黑的,相當於平衡二叉樹中的平衡因子),我想大家應該知道,這些地方 很費記憶體了吧,不說了……

12、   

      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的函式