std::map

來源:互聯網
上載者:User

映射和多重新對應基於某一類型Key的鍵集的存在,提供對T類型的資料進行快速和高效的檢索。對map而言,鍵只是指儲存在容器中的某一成員。Map不支援副本鍵,multimap支援副本鍵。Map和multimap對象包涵了鍵和各個鍵有關的值,鍵和值的資料類型是不相同的,這與set不同。set中的key和value是Key類型的,而map中的key和value是一個pair結構中的兩個分量。

1.map介紹

  使用map得包含map類所在的標頭檔: 

  #include <map> //注意,STL標頭檔沒有副檔名.h

1.1 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) //帶分配器

1.2 map定義

  1.2.1map的基本定義

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

  std:map<int, string> personnel;

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

  為了使用方便,可以對模板類進行一下類型定義:

  typedef map<int, CString> UDT_MAP_INT_CSTRING;

  UDT_MAP_INT_CSTRING enumMap; //後面會依此例說明

  1.2.2 map的嵌套定義

  map<sring,map<string,long> > //注意:最後兩個>之間有個空格

  map支援下標運算子operator[],用訪問普通數組的方式來訪問map;不過下標為map的鍵,在multimap中一個鍵可以對應多個不同的值。

2.map的方法2.1 在map中插入元素

  三種插入方式:

  2.1.1用insert方法插入pair對象:

   enumMap.insert(pair<int, Cstring>(1, “One”));

  2.1.2 用insert方法插入value_type對象:

   enumMap.insert(map<int, Cstring>::value_type (1, “One”));

  2.1.3 用數組方式插入值:

   enumMap[1] = "One";

  enumMap[2] = "Two";

  ......

  這樣非常直觀,但存在一個效能的問題。插入2時,先在enumMap中尋找主鍵為2的項,沒發現,然後將一個新的對象插入enumMap,鍵是2,值是一個Null 字元串,插入完成後,將字串賦為"Two"; 該方法會將每個值都賦為預設值,然後再賦為顯示的值,如果元素是類對象,則開銷比較大。用前兩種方法可以避免開銷。

2.2 尋找並擷取map中元素

  2.2.1下標操作符給出了獲得一個值的最簡單方法:

  CString tmp = enumMap[2];

  但是,只有當map中有這個鍵的執行個體時才對,否則會自動插入一個執行個體,值為初始化值。

  2.2.2我們可以使用find()和count()方法來發現一個鍵是否存在

  尋找map中是否包含某個關鍵字條目用find()方法,傳入的參數是要尋找的key,在這裡需要提到的是begin()和end()兩個成員,分別代表map對象中第一個條目和最後一個條目,這兩個資料的類型是iterator.

  int nFindKey = 2; //要尋找的Key

  //定義一個條目變數(實際是指標)

  UDT_MAP_INT_CSTRING::iterator it= enumMap.find(nFindKey);

  if(it == enumMap.end()) {

  cout<<"沒找到"<<endl;

  }

  else {

  cout<<"找到了"<<endl;

  }

  通過map對象的方法擷取的iterator資料類型是一個std::pair對象,包括兩個資料。

  iterator->first 關鍵字(key)

  iterator->second 儲存的資料(value)

2.3 從map中刪除元素

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

  該成員方法的定義如下:

  1.iterator erase(iterator it); //通過一個條目對象刪除

  2.iterator erase(iterator first, iterator last); //刪除一個範圍

  3.size_type erase(const Key& key); //通過關鍵字刪除

  2.3.2清除所有的元素clear()

  clear()就相當於 enumMap.erase(enumMap.begin(), enumMap.end());

2.4 map中swap的用法

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

  For example:

  #include <map>

  #include <iostream>

  using namespace std;

  int main( )

  {

  map <int, int> m1, m2, m3;

  map <int, int>::iterator m1_Iter;

  m1.insert ( pair <int, int> ( 1, 10 ) );

  m1.insert ( pair <int, int> ( 2, 20 ) );

  m1.insert ( pair <int, int> ( 3, 30 ) );

  m2.insert ( pair <int, int> ( 10, 100 ) );

  m2.insert ( pair <int, int> ( 20, 200 ) );

  m3.insert ( pair <int, int> ( 30, 300 ) );

  cout << "The original map m1 is:";

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

  cout << " " << m1_Iter->second;

  cout << "." << endl;

  // This is the member function version of swap

  //m2 is said to be the argument map; m1 the target map

  m1.swap( m2 );

  cout << "After swapping with m2, map m1 is:";

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

  cout << " " << m1_Iter -> second;

  cout << "." << endl;

  cout << "After swapping with m2, map m2 is:";

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

  cout << " " << m1_Iter -> second;

  cout << "." << endl;

  // This is the specialized template version of swap

  swap( m1, m3 );

  cout << "After swapping with m3, map m1 is:";

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

  cout << " " << m1_Iter -> second;

  cout << "." << endl;

  }

2.5 map的sort問題

  Map中的元素是自動按key升序排序,所以不能對map用sort函數:

  For example:

  #include <map>

  #include <iostream>

  using namespace std;

  int main( )

  {

  map <int, int> m1;

  map <int, int>::iterator m1_Iter;

  m1.insert ( pair <int, int> ( 1, 20 ) );

  m1.insert ( pair <int, int> ( 4, 40 ) );

  m1.insert ( pair <int, int> ( 3, 60 ) );

  m1.insert ( pair <int, int> ( 2, 50 ) );

  m1.insert ( pair <int, int> ( 6, 40 ) );

  m1.insert ( pair <int, int> ( 7, 30 ) );

  cout << "The original map m1 is:"<<endl;

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

  cout << m1_Iter->first<<" "<<m1_Iter->second<<endl;

  }

  The original map m1 is:

  1 20

  2 50

  3 60

  4 40

  6 40

  7 30

  請按任意鍵繼續. . .

2.6 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的函數

3.例子

  #include <iostream>

  #include <map>

  using namespace std;

  int main(void)

  {

  map<char,int,less<char> > map1;

  map<char,int,less<char> >::iterator mapIter;

  //char 是鍵的類型,int是值的類型

  //下面是初始化,與數組類似

  //也可以用map1.insert(map<char,int,less<char> >::value_type('c',3));

  map1['c']=3;

  map1['d']=4;

  map1['a']=1;

  map1['b']=2;

  for(mapIter=map1.begin();mapIter!=map1.end();++mapIter)

  cout<<" "<<(*mapIter).first<<": "<<(*mapIter).second;

  //first對應定義中的char鍵,second對應定義中的int值

  //檢索對應於d鍵的值是這樣做的:

  map<char,int,less<char> >::const_iterator ptr;

  ptr=map1.find('d');

  cout<<''\n''<<" "<<(*ptr).first<<" 鍵對應於值:"<<(*ptr).second;

  cin.get();

  return 0;

  }

  從以上常式中,我們可以看到map對象的行為和一般數組的行為類似。Map允許兩個或多個值使用比較操作符。下面我們再看看multimap:

  #include <iostream>

  #include <map>

  #include <string>

  using namespace std;

  int main(void)

  {

  multimap<string,string,less<string> >mulmap;

  multimap<string,string,less<string> >::iterator p;

  //初始化多重新對應mulmap:

  typedef multimap<string,string,less<string> >::value_type vt;

  typedef string s;

  mulmap.insert(vt(s("Tom "),s("is a student")));

  mulmap.insert(vt(s("Tom "),s("is a boy")));

  mulmap.insert(vt(s("Tom "),s("is a bad boy of blue!")));

  mulmap.insert(vt(s("Jerry "),s("is a student")));

  mulmap.insert(vt(s("Jerry "),s("is a beatutiful girl")));

  mulmap.insert(vt(s("DJ "),s("is a student")));

  //輸出初始化以後的多重新對應mulmap:

  for(p=mulmap.begin();p!=mulmap.end();++p)

  cout<<(*p).first<<(*p).second<<endl;

  //檢索並輸出Jerry鍵所對應的所有的值

  cout<<"find Jerry :"<<endl;

  p=mulmap.find(s("Jerry "));

  while((*p).first=="Jerry ")

  {

  cout<<(*p).first<<(*p).second<<endl;

  ++p;

  }

  cin.get();

  return 0;

  }

  在map中是不允許一個鍵對應多個值的,在multimap中,不支援operator[],也就是說不支援map中允許的下標操作。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.