map常用操作 添入 刪除 查詢 遍歷

2021-08-09 07:43:39 字數 1467 閱讀 7965

/map添入元素(1)利用pairmapma;

ma.insert(pair(2,"liming"));

或者ma.insert(make_pair(2,"liming"));(2)利用map的value_typemapma;

ma.insert(map::value_type(2,"liming"));(3)利用陣列mapma;

ma[2] = "liming";

maps;

str = "liming";

s[str] = 2;

另外,key值相同的時候無法新增到map中;

如果value對應的key值需要更新的時候,yua需要先獲取value值,然後刪去元素key,value對應元素,再重新插入新key,value對應的元素.

如果key對應的value值需要更新,可以直接賦值或操作,比如s[str] = 3;或者s[str]++;

map刪除元素

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

該成員方法的定義如下

(1)iterator erase(iterator it); //通過乙個條目物件刪除(2)iterator erase(iterator first, iterator last);//刪除乙個範圍(3)size_type erase(const key& key); //通過關鍵字刪除(4)map的清空函式clear()就相當於 enummap.erase(enummap.begin(), enummap.end());

//map查詢元素

(1)用count函式來判定關鍵字是否出現,其缺點是無法定位資料出現位置,由於map的特性,一對一的對映關係,就決定了count函式的返回值只有兩個,要麼是0,要麼是1,出現的情況,當然是返回1了

(2)用find函式來定位資料出現位置,它返回資料所在位置的迭代器,如果map中沒有要查詢的資料,它返回的迭代器等於end函式返回的迭代器.

//map的遍歷(1)前序遍歷mapma;

map::iterator na;

for (na = ma.begin(); na != ma.end(); na++)

cout << na->first << " " << na->second << endl;(2)後序遍歷mapma;

map::reverse_iterator na;

for (na = ma.rbegin(); na != ma.rend(); na++)

cout << na->first << " " << na->second << endl;mapma;

單鏈表建立,插入,刪除,查詢,遍歷操作

單鏈表建立,插入,刪除,查詢,遍歷操作 link.cpp 定義控制台應用程式的入口點。單鏈表 include stdafx.h include include using namespace std typedef struct node node 建立單鏈表 node create p new n...

單鏈表建立,插入,刪除,查詢,遍歷操作

link.cpp 定義控制台應用程式的入口點。單鏈表 include stdafx.h include include using namespace std typedef struct node node 建立單鏈表 node create p new node p data a p next ...

單鏈表建立,插入,刪除,查詢,遍歷操作!!!!

cpp view plain copy link.cpp 定義控制台應用程式的入口點。單鏈表 include stdafx.h include include using namespace std typedef struct node node 建立單鏈表 node create p new n...