2018年3月17日 星期六

程式設計I -- 字典(map)

使用map前要先引入
#include<map>


1. 建構map

map<string , int> amap;

amap 是一個 map, 鍵(key) 的型別是 string,值(value)的型別是 int 。
可以根據不同的需求,建構不同的型別。



2. 新增資料
在amap中新增一筆 key 為 "String" , value 為 1 的資料。

---方法一---
效率高但寫法複雜
amap.insert(make_pair("String", 1));

 ---方法二---
寫法簡單但效率慢
amap["String"] = 1;



3. 判斷資料在不在 map 中

---方法一---
使用find()看key是否存在於amap中

if (amap.find("String") == amap.end())
  cout << "沒找到" << endl;
else
  cout << "找到" << endl;

}

解釋:
find 會在 amap 中由開始 (begin() ) 找到尾巴 ( end() )。
如果沒找到,就會停在 end() 的地方。

---方法二---
使用count()看key是否存在於amap中

if (c.count(18) == 0)
  cout << "沒找到" << endl;
else
  cout << "找到" << endl;

}

解釋:
Count 會計算出現的次數
有出現      count() 回傳 1
沒有出現  count() 回傳 0



4. 輸出map內的資料

---方法一---
Cout<<amap["String"]<<endl;
輸出在amap中 key 為"String"的值(value)


---方法二---
使用迭代器

for (map<string, int>::iterator iter = amap.begin(); iter != amap.end(); iter++)
{
  if (iter->second > maxFreq)
  {
  maxFreq = iter->second;
  maxChar = iter->first;
  }

}

解釋:
iter->first      代表鍵 (key)
iter->second 代表值 (value)

---方法三---

for (pair<string, int> pp : amap)
{
  if (pp.second > maxFreq)
  {
  maxFreq = pp.second;
  maxChar = pp.first;
  }

}


5. 刪除元素
呼叫 earse 刪除key值。
amap.earse("String");

沒有留言:

張貼留言