map相关操作
? ? ? ? ? ?由于工作中經(jīng)常用到map來進(jìn)行數(shù)據(jù)保存和數(shù)據(jù)遍歷,這里來總結(jié)一下,先看看C++ Primer這么描述的。map屬于關(guān)聯(lián)容器,定義了一個(gè)關(guān)聯(lián)數(shù)組,類似vector,map是一個(gè)類模板。但是一個(gè)map要用兩個(gè)類型來定義:關(guān)鍵字的類型和關(guān)鍵值的類型。在一個(gè)map中,一個(gè)給定關(guān)鍵字只能出現(xiàn)一次,每個(gè)關(guān)鍵字關(guān)聯(lián)一個(gè)特定的值。解引用一個(gè)map迭代器會生成一個(gè)pair,它保存一個(gè)const關(guān)鍵字及其關(guān)聯(lián)的值。話不多說,看代碼,為了簡潔,我省略了頭文件。
1.map的遍歷
?
int main() {map<string,int> word={{"a",1},{"b",2}};map<string,int>::iterator IT;for(IT=word.begin();IT!=word.end();IT++){cout<<IT->first<<','<<IT->second<<endl;}return 0; }打印:a,1
?
? ? ? ? ? ? b,2
2.map的插入操作(insert)。insert函數(shù)操作的返回值是一個(gè)pair,其first成員是一個(gè)迭代器,指向具有給定關(guān)鍵字的元素,second的成員是一個(gè)bool值
?
int main() {map<string,int> word;pair<map<string,int>::iterator,bool> ret;//定義insert的返回值ret=word.insert(pair<string,int>("a",1));if(ret.second){cout<<"yes"<<endl;cout<<ret.first->second<<endl;}return 0; }打印:yes
?
? ? ? ? ? ? 1
3.map的刪除操作(erase)
?
int main() {map<string,int>word={{"a",1},{"b",2},{"c",3}};int num=word.erase("a")//利用關(guān)鍵字刪除,返回刪除元素的數(shù)量。雞肋cout<<num<<endl;map<string,int>::iterator IT=word.begin();//注意這里IT重新賦值,因?yàn)榍懊鎰h除過一個(gè)迭代器,指向不明確了map<string,int>::iterator IT1;IT1=word.erase(IT);//word.erase.(IT++) 這樣。返回的迭代器仍指向下一個(gè)迭代器cout<<IT1->first<<','<<IT1->second<<endl;IT=word.begin();IT1=word.end();word.erase(IT,IT1);//根據(jù)范圍迭代器進(jìn)行刪除,返回IT1return 0; }打印:1
?
? ? ? ? ? ? b,2
IT++是自加操作,將IT指向下一個(gè)地址并且返回IT原來的副本。參數(shù)的處理優(yōu)先于函數(shù)的調(diào)用。不信看
?
void func(map<string,int>::iterator it) {cout<<it->first<<','<<it->second<<endl; }int main() {map<string,int>word={{"a",1},{"b",2}};map<string,int>::iterator IT=word.begin();func(IT++);cout<<IT->first<<','<<IT->second<<endl;return 0; }打印:a,1
?
? ? ? ? ? ? b,2
?
4.map中元素的查找(find),返回一個(gè)迭代器,指向第一個(gè)關(guān)鍵字為key的元素,沒找到則返回map的尾部迭代器
?
int main() {map<string,int>word={{"a",1}};map<string,int>::iterator IT;IT=word.find("a");cout<<IT->first<<','<<IT->second<<endl;return 0; }打印:a,1
?
?map還有clear(),count(),empty(),size(),swap()等函數(shù)
平常學(xué)習(xí)中,map中對應(yīng)的關(guān)鍵值只存放一個(gè)元素。實(shí)際工作中需要存放多個(gè)元素,此時(shí)關(guān)鍵值變?yōu)榻Y(jié)構(gòu)體了。
struct Node {int data;int data1; };int main() {map<int,Node> Map;//struct標(biāo)識不需要寫進(jìn)去Map.insert(pair<int,Node>(1,{2,3}));map<int,Node>::iterator it=Map.begin();cout<<it->second.data<<','<<it->second.data1<<endl;return 0; }打印:2,3
?
?
?
?
?
?
?
?
?
總結(jié)
- 上一篇: sscanf简单用法
- 下一篇: sprintf,sscanf,snpri