STL Map使用詳解(一)(包含如何按關鍵字降序排列)


2013-09-11 14:26:09

轉自:http://blog.csdn.net/bichenggui/article/details/4215344

 Map是一種關聯容器,用來存儲key-value數據。其中的key是用來查找的關鍵字,value是實際存放的值。

一個特定的關鍵字只能與一個唯一的值相聯系。map是由一對一對的鍵值(key/value)所組成的排序結構體,

鍵值是讀一無二的(unique)的。

  map通常是以平衡二叉查找樹來實現的,因此map對插入,刪除,查找能保證log(N)的時間復雜度。對於

海量的數據的插入和查詢,map是一個不錯的選擇。

  本文將對map的常見操作進行講解。不當之處,歡迎批評指正(bicheng.gui@gmail.com).

  1. map的構造:

map提供了以下模板構造函數:

   template<class T1, class T2>

   map();                         // 默認構造函數

   map(const map& m)    // 拷貝構造函數

   map(iterator begin, iterator end );  //區間構造函數

   map(iterator begin, iterator end, const traits& _compare) //帶比較謂詞的構造函數

   map(iterator begin, iterator end, const traits& _compare, const allocator& all) //帶分配器

例子:

#include <map>

#include <iostream>

using namespace std; 

typedef pair<int,int> int_pair;

map<int,int>::iterator itr1;

map<int,int> m1; //默認升序,從小到大

m1[1] = 10; 

m1[2] = 20;

m1[3] = 30;

//輸出結果10 20 30,有換行

for (itr1 = m1.begin(); itr1 != m1.end(); ++itr1)

{

    cout << itr1->second << endl;

}

map<int,int,greater<int>> m2; //降序的map

map<int,int,greater<int>>::iterator itr2;

m2[1] = 10;  //插入鍵值為1,value為10的元素,multimap不支持operator[]

m2.insert(int_pair(2,20)); //map的valuetype是pair(t1,t2);

m2[3] = 30;

//輸出30,20,10

for (itr2 = m2.begin(); itr2 != m2.end(); ++itr2)

{

    cout << itr2->second << endl;

}

//利用m1的內存分配器構造一個m3

map<int,int>::allocator_type al = m1.get_allocator();

map<int,int> m3(less<int>(), al);

//根據m1拷貝一個m4

map<int,int> m4(m1); //謂詞和類型必須要匹配。

//根據兩個iterator構造map

map<int,int,greater<int>> m5(m2.begin(), m2.end());

//輸出m5, 30,20,10 ,帶換行。

for (itr2 = m5.begin(); itr2 != m5.end(); ++itr2)

{

    cout << itr2->second << endl;

}

以上代碼需要VS2005以上編譯器。

2. map的常見操作: 

map支持常見的迭代器接口,例如begin(),end(),rbegin(),rend(). 

empty()        判斷map是否為空。為空的話返回真。

size()           返回map的長度

maxsize()    返回map能容納的最大的元素個數,根據編譯器和平台而變化。

3. pair<iterator, bool> insert(iterator where,const value_type& val)

可以插入一個對象,一個對象的若干份拷貝,或者一個范圍內的對象.

insert函數把對象插入到where所指的元素之前。

示例代碼:

map<int,int>::iterator itr1,itr2;

map<int,int> m1,m2;

typedef pair<int,int> int_pair;

m1.insert( int_pair( 1, 10) );

m1.insert( int_pair( 3, 30) );

由於map容器不允許鍵值重復,在執行插入操作后,可以根據返回值獲取操作是否成功。

返回值是一個迭代器和布爾值的pair,迭代器指向map中具有該值的元素,布爾值表示是否插入成功。

如果布爾值為true,表示插入成功,則迭代器為新插入值在map中的位置。

如果布爾值為false,表示插入失敗(已經存在該值),迭代器為原有值在map中的位置。

pair<map<int,int>::iterator, bool> insertresult;

insertresult = m1.insert(int_pair(1,10));

if (insertresult->second)

{

  //插入成功

}

else

{

  //插入失敗

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM