C++|STL學習筆記-map的屬性(大小以及是否存在)
阿新 • • 發佈:2018-12-21
目錄
1.size()的用法
map的property
map屬性
1.沒有容量;
2.得到元素的個數size()
這裡給出呼叫他size()的例子,原始碼如下:
/************************************************************************/ /* map property */ /************************************************************************/ #include <map> #include <iostream> #include <algorithm> using namespace std; typedef pair<int, char> in_pair; typedef pair<map<int, char>::iterator, bool> in_pair_bool; void judgeOk(in_pair_bool pr){ if(pr.second){ cout << "insert the success!" << endl; } else{ cout << "insert the failture!" << endl; } } void mapProperty(){ map<int, char> mp; pair<map<int, char>::iterator, bool> pr; pr = mp.insert(in_pair(1, 'a')); judgeOk(pr); pr = mp.insert(in_pair(2, 'b')); judgeOk(pr); pr = mp.insert(in_pair(3, 'c')); judgeOk(pr); pr = mp.insert(in_pair(4, 'd')); judgeOk(pr); pr = mp.insert(in_pair(2, 'e')); judgeOk(pr); cout << "The map size is " << mp.size() << endl; } void main(){ mapProperty(); getchar(); }
執行截圖如下:
2.多多使用count(xxx)進行判斷
這裡有個小知識點使用count判斷map是否存在,不存在返回0
個人感覺STL中map的這一點就沒有QTL好用了,
QTL是這樣的命名:
是不是感覺QTL更加通俗易懂:
下面給出STL中關於count的栗子:
/************************************************************************/ /* map property */ /************************************************************************/ #include <map> #include <iostream> #include <algorithm> using namespace std; typedef pair<int, char> in_pair; typedef pair<map<int, char>::iterator, bool> in_pair_bool; void judgeOk(in_pair_bool pr){ if(pr.second){ cout << "insert the success!" << endl; } else{ cout << "insert the failture!" << endl; } } void mapProperty(){ map<int, char> mp; pair<map<int, char>::iterator, bool> pr; pr = mp.insert(in_pair(1, 'a')); judgeOk(pr); pr = mp.insert(in_pair(2, 'b')); judgeOk(pr); pr = mp.insert(in_pair(3, 'c')); judgeOk(pr); pr = mp.insert(in_pair(4, 'd')); judgeOk(pr); pr = mp.insert(in_pair(2, 'e')); judgeOk(pr); cout << "The map size is " << mp.size() << endl; cout << "The use of count() function" << endl; if(mp.count(3)){ cout << "presence key three" << endl; } map<int, char>::iterator it = mp.begin(); for(it; it != mp.end(); it++){ cout << it->first << "\t" << it->second << endl; } } void main(){ mapProperty(); getchar(); }
執行截圖如下: