進階篇_map容器(儲存鍵值對)
阿新 • • 發佈:2019-01-28
1. 三種向map容器插入資料對的方法(等效)
map<int, Employee> mapEmployee; Employee emp1; mapEmployee.insert(pair<int, Employee>(1, emp1)); //法一插入:使用pair建立員工號1和員工物件emp1的對映關係,並插入map容器中 mapEmployee.insert(map<int, Employee>::value_type(1, emp1)); //法二插入:使用value_type型別實現資料的插入 mapEmployee[1983] = emp1; //法三插入:向map容器中插入一個數據對(1983, emp1)
2. 根據鍵找到對應的值
a. 通過迭代器輸出資料對的鍵和值(遍歷):
for(map<int, Employee>::iterator it; it!=mapEmployee.end(); ++it)
{
cout<<it->first<<endl; //通過迭代器輸出資料對的鍵和值
cout<<it->second.getname()<<endl;
}
b.通過 map容器的find()函式查詢某一個鍵(也通過迭代器,這種方式用的更多):
int findkey = 1; //定義要查詢的鍵 map<int, Employee>::iterator it = mapEmployee.find(findkey); cout<<it->first<<" "<<it->second.getname()<<endl;
3. 訪問某個範圍的資料對
以上程式碼中,分別使用了lower_bound()與upper_bound()函式來獲得指向這個範圍的起始位置和終止位置的迭代器int fromkey = 1; int tokey = 1000; //定義鍵的範圍 map<int, Employee>::iterator itfrom = mapEmployee.lower_bound(fromkey); map<int, Employee>::iterator itto = mapEmployee.upper_bound(tokey); //用迭代器表示起始位置和終止位置 for(map<int, Employee>::iterator it = itfrom; it!=itto; ++it) { cout<<it->first<<endl; //輸出範圍內的所有資料 } mapEmployee.erase(itfrom, itto);//刪除範圍內的所有資料