转载自:https://www.cnblogs.com/empty16/p/6395813.html
在阅读SSD代码中发现作者使用了C++中的map方法,因此搜索该关联式容器的使用方法,在这里一并总结。
一、Map 簡介
Map是STL的一個容器,它提供一對一的hash。
- 第一個可以稱為關鍵字(key),每個關鍵字只能在map中出現一次,
- 第二個可能稱為該關鍵字的值(value)
Map以模板(泛型)方式實現,可以儲存任意類型的變數,包括使用者自定義的資料型態。Map主要用於資料一對一映射(one-to-one)的情況,map內部的實現自建一顆紅黑樹,這顆樹具有對數據自動排序的功能。比如一個班級中,每個學生的學號跟他的姓名就存在著一對一映射的關係。
二、成員函式概觀 與 常用程式寫法
引入头文件:#include <map>
1. 变量声明
map<string, string> mapStudent;
2. 插入元素
//用insert函數插入pair
mapStudent.insert(pair<string, string>("r000", "student_zero"));
//用"array"方式插入
mapStudent["r123"] = "student_first";
mapStudent["r456"] = "student_second";
3. 查找
出現時,它返回資料所在位置,如果沒有,返回iter與end函數返回相同
iter = mapStudent.find("r123");
if(iter != mapStudent.end())
cout<<"Find, the value is"<<iter->second<<endl;
else
cout<<"Do not Find"<<endl;
4. 刪除與清空
清空map中的數據可以用clear()函數,判定map中是否有數據可以用empty()函數,它返回true則說明是空map,而資料的刪除要用到erase函數,它有三個overload的函數。
//迭代器刪除
iter = mapStudent.find("r123");
mapStudent.erase(iter);
//用關鍵字刪除
int n = mapStudent.erase("r123");//如果刪除了會返回1,否則返回0
//用迭代器範圍刪除 : 把整個map清空
mapStudent.erase(mapStudent.begin(), mapStudent.end());
//等同於mapStudent.clear()
刪除要注意的是,也是STL的特性,刪除區間是一個前閉後開的集合其他一些函數用法
5.map循环遍历
for (iter = mapStudent.begin(); iter != mapStudent.end();iter++)
{
Log::Trace("", "", "当前key={0}", iter->first);
Log::Trace("", "", "当前value={0}", iter->second);
}