STL中map的用法簡單介紹

2021-09-03 01:12:56 字數 2937 閱讀 1557

一、map的插入,有三種方法

mapmapstudent

1)mapstudent.insert(map::value_type(keys,value));

2)mapstudent.insert(pair(keys,value));

3) mapstudent[1] = value;  

1、map::value_type(keys,value)

#include#include#includeusing namespace std;

int main()

2、 mapstudent.insert(pair(keys,value))

#include#include#includeusing namespace std;

int main()

3、mapstudent[1] = value;  

#include#include#includeusing namespace std;

int main()

區別:如果map中存在關鍵字,使用insert插入方法不能改變關鍵字對應的值,但使用陣列的插入方式就可以覆蓋原來關鍵字對應的值,比如在下列兩句**,第二句不起作用:

mapstudent.insert(map::value_type (1, "student_one"));

mapstudent.insert(map::value_type (1, "student_two"));

二、使用pair獲取是否插入成功

使用**:

pair::iterator, bool> insert_pair;

insert_pair = mapstudent.insert(map::value_type (1, "student_one"));

通過pair的第二個變數來知道是否插入成功,它的第乙個變數返回的是個map的迭代器,如果插入成功的話insert_pair.second應該是true的,否則為false。

#include#include#includeusing namespace std;

int main()

三、遍歷map的方法

1、用正向迭代器,map::iterator iter 的方式

map::iterator i;

for (i = mapstudent.begin(); i != mapstudent.end(); i++)

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

2、用反向迭代器,map::reverse_iterator iter的方法

#include#include#includeusing namespace std;

int main()

3、利用陣列的形式訪問

#include#include#includeusing namespace std;

int main()

四、查詢並獲取map中的元素

1、使用mapstudent.count(key),key是關鍵字,查詢某個關鍵字是否在map中出現,返回1(存在)或者0(不存在)

2、使用mapstudent.find(key),key是關鍵字,返回乙個迭代器,如果存在,迭代器指向資料所在位置,如果不存在,迭代器為end位置的迭代器

#include#include#includeusing namespace std;

int main()

3、使用 lower_bound,upper_bound和qual_range函式

參考:

mapstudent.lower_bound(key)返回map中第乙個大於或者等於key的迭代器

mapstudent.upper_bound(key)返回map中第乙個大於key的迭代器

mapstudent.equal_range(key)返回乙個pair,pair中的第乙個變數是lower_bound()返回的迭代器,第二個變數是upper_bound()返回的迭代器。如果不存在key = 2,存在key=3,那麼lower_bound(2)和upper_bound(2)返回的都是3,也就是equal_range(2)返回的pair中的兩個變數相等。因此,可以通過equal_range(key)來判斷是否存在某個key。

#include#include#includeusing namespace std;

int main()

四、從map中刪除元素

分別檢視map刪除元素的成員函式的宣告如下:

1、 iterator erase(iterator it);  //刪除 it 迭代器指向位置的元素

2、iterator erase(iterator first,iterator last);  //刪除 first~last 範圍的元素

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

4、clear()相當於enummap.erase(enummap.begin(),enummap.end())

#include#include#includeusing namespace std;

int main()

五、map中的排序sort

參考:參考:

參考:

STL 中 map 的用法

說明 如果你具備一定的 c template知識,即使你沒有接觸過stl,這個文章你也應該可能較輕易的看懂。本人水平有限,不當之處,望大家輔正。一 map概述 map是stl的乙個關聯容器,它提供一對一 其中第乙個可以稱為關鍵字,每個關鍵字只能在map中出現一次,第二個可能稱為該關鍵字的值 的資料處...

STL中map用法詳解

map是stl的乙個關聯容器,它提供一對一 其中第乙個可以稱為關鍵字,每個關鍵字只能在 map中出現一次,第二個可能稱為該關鍵字的值 的資料處理能力,由於這個特性,它完成有可能在我們處理一對一資料的時候,在程式設計上提供快速通道。這裡說 下map內部資料的組織,map內部自建一顆紅黑樹 一種非嚴格意...

STL中map用法詳解

說明 如果你具備一定的c template知識,即使你沒有接觸過stl,這個文章你也應該可能較輕易的看懂。本人水平有限,不當之處,望大家輔正。一 map概述 map是stl的乙個關聯容器,它提供一對一 其中第乙個可以稱為關鍵字,每個關鍵字只能在map中出現一次,第二個可能稱為該關鍵字的值 的資料處理...