C++STL—map的使用

最近寫的一道題用到了STL中的map,這部份內容以前沒有系統學過,這裏就簡單概括一下吧。html

資料來源:c++

https://www.w3cschool.cn/cpp/cpp-fu8l2ppt.html數組

http://c.biancheng.net/view/338.htmlspa

http://www.javashuo.com/article/p-riqmtnng-mo.html.net

經常使用操做:指針

  1. 添加元素:能夠用Insert,也能夠下標添加

 

   map<int ,string> maplive;  
   1.maplive.insert(pair<int,string>(102,"aclive"));
   2.maplive.insert(map<int,string>::value_type(321,"hai"));
   3, maplive[112]="April";//map中最簡單最經常使用的插入添加!

 

  2.查找:注意,map中元素是key-value配對的,要查找一個元素,須要提供它的key。map的內部是以平衡二叉樹形式儲存的,因此查找的速度爲O(logn),速度很快。code

  另外,這也意味着,map內部的元素是有序的!因此咱們若是隻是須要一個按key排序的輸出的話,不須要對map進行排序,直接遍歷輸出便可。htm

  3.遍歷:map的遍歷是經過迭代器完成的:blog

1) 正向迭代器,定義方法以下:()排序

容器類名::iterator  迭代器名;


2) 常量正向迭代器,定義方法以下:

容器類名::const_iterator  迭代器名;


3) 反向迭代器,定義方法以下:

容器類名::reverse_iterator  迭代器名;


4) 常量反向迭代器,定義方法以下:

容器類名::const_reverse_iterator  迭代器名;

遍歷過程:

map<int, int>::iterator iter;
    iter = _map.begin();
    while(iter != _map.end()) {
        cout << iter->first << " : " << iter->second << endl;
        iter++;
    }

注意這裏的map.end(),它和map.begin(),map.lower_bound(),map.upper_bound()同樣,返回的是一個迭代器而不是元素自己。

*易錯點:

map::lower_bound(key):返回map中第一個大於或等於key的迭代器指針

map::upper_bound(key):返回map中第一個大於key的迭代器指針

另外:

  1.對於map中沒有的key,若是訪問的話返回的value爲0;

  2.map雖然有「下標」訪問而且內部元素是有序的,但這不表明能夠實現相似數組的下標訪問,即訪問第0個、第1個·····第n個元素。

  3.map中的end()指向的不是最後一個元素,而是最後一個元素的下一個元素,這樣是爲了遍歷時的方便,即便用while(iter != _map.end())的條件變量時能夠遍歷到最後一個元素。

舉個例子:

 

#include<bits/stdc++.h>
using namespace std;
int main(){
map<int,int>testmap;
testmap[0]=8;
testmap[2]=9;
//重要!end()指向的是下一個而非尾部
cout<<"begin's first:" <<testmap.begin()->first<<"begin's second:"<<testmap.begin()->second<<" end's first: "<<testmap.end()->first<<endl;
cout<<testmap[1]<<endl;
getchar();
}

 

結果爲:

map<int ,string> maplive; 1.maplive.insert(pair<int,string>(102,"aclive")); 2.maplive.insert(map<int,string>::value_type(321,"hai")); 3, maplive[112]="April";//map中最簡單最經常使用的插入添加!

相關文章
相關標籤/搜索