C++ map迭代器的基本操作和使用
1、map簡介
map是一類關聯式容器,增加和刪除節點對迭代器的影響很小。除了對操作節點有影響,對其他的節點沒有什麼影響。map主要建立了key到value的對映。key和value可以是任意型別。
注意:對於迭代器來說,可以修改實值,而不能修改key。
2、map的功能
根據key值快速查詢記錄,查詢的複雜度基本是Log(N),如果有1000個記錄,最多查詢10次。
快速插入Key - Value 記錄。
快速刪除記錄
根據Key 修改value記錄。
遍歷所有記錄。
3、使用map
map<key,value> key-first, value-second
為了使用方便,可以對模板類進行一下型別定義,
typedef map<int, CString> myMap;
myMAP enumMap;
4、在map中插入元素
改變map中的條目非常簡單,因為map類已經對[]操作符進行了過載
enumMap[1] = "One";
enumMap[2] = "Two";
這樣非常直觀,但存在一個性能的問題。插入2時,先在enumMap中查詢主鍵為2的項,沒發現,然後將一個新的物件插入enumMap,鍵是2,值是一個空字串,插入完成後,將字串賦為"Two"; 該方法會將每個值都賦為預設值,然後再賦為顯示的值,如果元素是類物件,則開銷比較大。我們可以用以下方法來避免開銷:
enumMap.insert(map<int, CString> :: value_type(2, "Two"))
5、查詢並獲取map中的元素
下標操作符給出了獲得一個值的最簡單方法:
CString tmp = enumMap[2];
但是,只有當map中有這個鍵的例項時才對,否則會自動插入一個例項,值為初始化值。
查詢函式:Find(key)和Count()。
begin()和end()兩個成員,分別代表map物件中第一個條目和最後一個條目,這兩個資料的型別是iterator
int nFindKey = 2; //要查詢的Key
//定義一個條目變數(實際是指標)
myMap::iterator it= enumMap.find(nFindKey);
if(it == enumMap.end()) {
//沒找到
}
else {
//找到
}
通過map物件的方法獲取的iterator資料型別是一個std::pair物件。
iterator包括兩個資料 iterator->first 和 iterator->second 分別代表關鍵字key和儲存的資料value。
6、從map中刪除元素
移除某個map中某個條目用erase(),注意引數是條目iterator
該成員方法的定義如下
iterator erase(iterator it):通過一個條目it物件刪除
iterator erase(iterator first, iterator last):刪除一個範圍 [first,end]裡面的元素
size_type erase(const Key& key):通過關鍵字key刪除
clear():刪除所有元素
#include <iostream> #include <map> #include <string> using namespace std; void map_insert(map<string,string> *mapStudent, string index, string x){ mapStudent->insert(map<string,string>::value_type(index,x)); } int main(){ char tmp[32]=""; map<string, string> mapS; map_insert(&mapS,"192.168.0.128","xiong"); map_insert(&mapS,"192.168.200.3","feng"); map_insert(&mapS,"192.168.200.33","xiongfeng"); map<string, string>::iterator iter; cout<<"we have there elements"<<endl; cout<<"----------------------"<<endl; iter=mapS.find("192.168.200.33"); //查詢 cout<<"查詢"<<endl; if(iter!=mapS.end()){ cout<<"find the element"<<endl; cout<<"it is:"<<iter->second<<endl; }else{ cout<<"not find the element"<<endl; } //遍歷 cout<<"遍歷"<<endl; for(iter=mapS.begin();iter!=mapS.end();iter++){ cout<<"| "<<iter->first<<" | "<<iter->second<<" |"<<endl; } //刪除 cout<<"刪除"<<endl; iter=mapS.find("192.168.200.33"); if(iter!=mapS.end()){ cout<<"find the element"<<endl; cout<<"delete the element"<<endl; mapS.erase(iter); }else{ cout<<"not find the element"<<endl; } for(iter=mapS.begin();iter!=mapS.end();iter++){ cout<<"| "<<iter->first<<" | "<<iter->second<<" |"<<endl; } return 0; }