1

# Map簡介

map裡面的元素存兩個值，

map非常類似於python語法的字典(dict)

map的優點是可以在O(log n)的時間做插入與查找，

## 一、引入函式庫

``````#include <map>
using namespace std;
``````

## 二、宣告

map的宣告方式如下:

``````map<string, string> myMap;
``````

## 宣告的同時初始化

``````map<string, string> myMap = { {"s", "黑桃"}, {"d", "方塊"} };
``````

``````map<string, string> myMap =
{
{"s", "黑桃"},
{"d", "方塊"},
{"h", "紅心"},
{"c", "梅花"}
};
``````

## 三、插入元素

``````map<string, string> myMap;
myMap.insert(pair<string, string>("s", "黑桃"));
``````

``````map<string, string> myMap;
myMap["s"] = "黑桃";
``````

## 四、查詢元素

(map則是用key去查詢value的值)

``````#include <map>
#include <string>
#include <iostream>
using namespace std;

int main()
{
map<string, string> myMap = { {"s", "黑桃"}, {"d", "方塊"} };
cout << myMap["h"] << endl; //因為myMap還沒有key為"h"的元素，不印出東西
cout << myMap["d"] << endl; //方塊
return 0;
}
``````

``````#include <map>
#include <string>
#include <iostream>
using namespace std;

int main()
{
map<string, string> myMap = { {"s", "黑桃"}, {"d", "方塊"} };
auto iter = myMap.find("d");
if(iter != myMap.end())
cout<<"key "<< iter->first << " 對應的value值為: "<<iter->second<<endl;
else
cout<<"找不到元素"<<endl;
return 0;
}
``````

## 五、遍歷元素

``````#include <map>
#include <string>
#include <iostream>
using namespace std;

int main()
{
map<string, string> myMap =
{
{"s", "黑桃"},
{"d", "方塊"},
{"h", "紅心"},
{"c", "梅花"}
};
for (auto it = myMap.begin(); it != myMap.end(); it++) {
cout<<it->first<<" "<<it->second<<endl;
}
return 0;
}
``````

`c 梅花`
`d 方塊`
`h 紅心`
`s 黑桃`

## 六、刪除元素

### 用迭代器刪除

``````auto iter = myMap.find("s");
myMap.erase(iter);
``````

### 用關鍵字刪除

``````int n = myMap.erase("s");//如果刪除了會返回1，否則返回0
``````

### 迭代器範圍刪除

``````myMap.erase(myMap.begin(), myMap.end()); //相當於myMap.clear()，清空元素
``````