C++標準模板庫map的常用操作
更新時間:2018年12月21日 11:23:07 作者:蝸牛201
今天小編就為大家分享一篇關于C++標準模板庫map的常用操作,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
一:介紹
map是STL的關聯(lián)式容器,以key-value的形式存儲,以紅黑樹(平衡二叉查找樹)作為底層數(shù)據(jù)結構,對數(shù)據(jù)有自動排序的功能。
命名空間為std,所屬頭文件<map> 注意:不是<map.h>
二:常用操作
容量:
- a.map中實際數(shù)據(jù)的數(shù)據(jù):map.size()
- b.map中最大數(shù)據(jù)的數(shù)量:map.max_size()
- c.判斷容器是否為空:map.empty()
修改:
- a.插入數(shù)據(jù):map.insert()
- b.清空map元素:map.clear()
- c.刪除指定元素:map.erase(it)
迭代器:
- a.map開始指針:map.begin()
- b.map尾部指針:map.end() 注:最后一個元素的下一個位置,類似為NULL,不是容器的最后一個元素
三:存儲
map<int, string> map1; //方法1: map1.insert(pair<int, string>(2, "beijing")); //方法2: map1[4] = "changping"; //方法3: map1.insert(map<int, string>::value_type(1, "huilongguan")); //方法4: map1.insert(make_pair<int, string>(3, "xierqi"));
四:遍歷
for (map<int, string>::iterator it=map1.begin(); it!=map1.end(); it++)
{
cout << it->first << ":" << it->second << endl;
}
五:查找
string value1 = map1[2];
if (value1.empty())
{
cout << "not found" << endl;
}
//方法2
map<int, string>::iterator it = map1.find(2);
if (it == map1.end())
{
cout << "not found" << endl;
}
else
{
cout << it->first << ":" << it->second << endl;
}
六:修改
//修改數(shù)據(jù) map1[2] = "tianjin";
七:刪除
//方法1 map1.erase(1); //方法2 map<int, string>::iterator it1 = map1.find(2); map1.erase(it1);
總結
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對腳本之家的支持。如果你想了解更多相關內(nèi)容請查看下面相關鏈接
相關文章
C++開發(fā)在IOS環(huán)境下運行的LRUCache緩存功能
本文著重介紹如何在XCODE中,通過C++開發(fā)在IOS環(huán)境下運行的緩存功能。算法基于LRU,最近最少使用,需要的朋友可以參考下2012-11-11

