C++ 的 STL-map 排序功能很方便,是我很常用的容器。在這裡列出一些常用的用法。
1. 基本用法
#include <iostream>
#include <map>
using namespace std;
int main()
{
//宣告一個 map,塞一些資料
map<int, int> mapTest;
for(int i = 0 ; i < 10 ; i++)
mapTest[i] = i*100;
//如果 key 重覆,資料會被蓋過去
mapTest[5] = 5000;
//印出來
map<int, int>::iterator it;
for (it = mapTest.begin(); it != mapTest.end(); it++)
cout << it->first << " " << it->second << endl;
system("pause");
return 0;
}

2. 用指標來使用 map
#include <iostream>
#include <map>
using namespace std;
typedef map<int, int> TEST_MAP;
int main()
{
TEST_MAP* mapTest = new TEST_MAP();
//也可以用這種方式塞資料
for (int i = 0; i < 10; i++)
mapTest->insert(pair<int, int>(i, i * 100));
map<int, int>::iterator it;
for (it = mapTest->begin(); it != mapTest->end(); it++)
cout << it->first << " " << it->second << endl;
cout << "mapTest[0] = " << (*mapTest)[0] << endl;
delete mapTest;
system("pause");
return 0;
}

3. 判斷容器裡有沒有,然後塞入新資料
map<int, int> mapTest;
if(mapTest.find(15) == mapTest.end())
mapTest[15] = 1500;
4. 試圖去取沒有被塞值的索引
如果試圖去取沒有被塞值的索引
會產生一個資料,裡面放著無法預期的值
千萬要避免這種情況
所以在取值之前一定要先用 find 來確定
#include <iostream>
#include <map>
using namespace std;
int main()
{
//宣告一個 map,塞一些資料
map<int, int> mapTest;
for (int i = 0; i < 10; i++)
mapTest[i] = i * 100;
//這裡是錯誤示範
//如果試圖去取沒有被塞值的索引
//會產生一個資料,裡面放著無法預期的值
//千萬要避免這種情況
//所以在取值之前一定要先用 find 來確定
cout << mapTest[20] << endl;
//全部印出來
cout << "--" << endl;
map<int, int>::iterator it;
for (it = mapTest.begin(); it != mapTest.end(); it++)
cout << it->first << " " << it->second << endl;
system("pause");
return 0;
}

5. 刪除資料
map<int, int>::iterator it;
if ((it = mapTest.find(1)) != mapTest.end())
mapTest.erase(it);
6. 反向存取
map 預設排序是由小至大
如果要取得由大至小的資料
可使用反向存取器 reverse_iterator
#include <iostream>
#include <map>
using namespace std;
int main()
{
map<int, int> mapTest;
for (int i = 0; i < 10; i++)
mapTest[i] = i * 100;
//反向存取
cout << "reverse" << endl;
map<int, int>::reverse_iterator rit;
for (rit = mapTest.rbegin(); rit != mapTest.rend(); rit++)
cout << rit->first << " " << rit->second << endl;
system("pause");
return 0;
}

C++ 的 STL-在迴圈中刪除 iterator
https://husking-studio.com/cpp-iterator-erase-in-loop/