map 05 ac03 map cpp map include map

  • Slides: 12
Download presentation

【 map 說明範例 】 // 05 ac_03 map. cpp map說明範例 #include <map> #include <string>

【 map 說明範例 】 // 05 ac_03 map. cpp map說明範例 #include <map> #include <string> #include <iostream> using namespace std; int main() { //1. 宣告及設定初值 map<int, string> m; map<int, string>: : iterator iter, beg, end; //2. 添加元素,共有三種方法,以下是常見的兩種方法 //(1)陣列:具有覆蓋功能,相同的key,會取最後一個value //(2)pair:沒有覆蓋功能,無法插入,相同的key,會取第一個value m[0] = "student_one"; m[1] = "student_two"; m[2] = "student_three"; m. insert(pair<int, string>(5, "Fear Kubrick")); m. insert(pair<int, string>(2, "Akemi Homura")); m. insert(pair<int, string>(-1, "Eren Jaeger")); m. insert(pair<int, string>(99, "lin")); cout << m. size() << endl;

【 map 說明範例 】 //5. 刪除 //單鍵刪除 iter = m. find(1); if (iter !=

【 map 說明範例 】 //5. 刪除 //單鍵刪除 iter = m. find(1); if (iter != m. end()) m. erase(iter); cout << m. size() << endl; for (iter = m. begin(); iter != m. end(); iter++) cout << iter->first << " " << iter->second << endl; //範圍刪除 beg = m. find(-1); end = m. find(5); if (beg != m. end() && end != m. end()) m. erase(beg, end); //刪除beg到end之前的元素,不包括end //若想刪除end的鍵值,可以這麼寫:m. erase(beg, ++end); //或者將上面的改為end = m. upper_bound(5); cout << m. size() << endl; for (iter = m. begin(); iter != m. end(); iter++) cout << iter->first << " " << iter->second << endl; //6. 判空與清空 if (!m. empty()) m. clear(); cin. get(); return 0; }

【map解題範例】 Zerojudge a 743 (Uva 10420 - List of Conquests) // 05 ac_05 map_ex.

【map解題範例】 Zerojudge a 743 (Uva 10420 - List of Conquests) // 05 ac_05 map_ex. cpp Zerojudge a 743 List of Conquests #include <iostream> #include <map> #include <sstream> using namespace std; map<string, int> m; map<string, int>: : iterator it; int main () { int n; string s, ns; cin >> n; cin. get(); while(n--) { getline(cin, s); stringstream ss(s); ss >> ns; if(m. find(ns) == m. end()) m[ns] = 1; else m[ns]++; } for(it=m. begin(); it!=m. end(); it++) cout << it->first << " " << it->second << endl; return 0; }

【 map 練習範例】 zerojudge b 162 NOIP 2007 1. 统计数字 zerojudge d 244 一堆石頭

【 map 練習範例】 zerojudge b 162 NOIP 2007 1. 统计数字 zerojudge d 244 一堆石頭 zerojudge b 198 C. 計票程式 zerojudge d 217 (Uva 489 - Hangman Judge ) zerojudge d 492 (Uva 10226 - Hardwood Species ) zerojudge a 743 (Uva 10420 - List of Conquests ) Uva 630 - Anagrams(II) Uva 755 - 487 -3279 Uva 10205 - Stack 'em Up Uva 10282 - Babelfish Uva 10295 - Hay Points Uva 11503 - Virtual Friends

To be Continue… 回目錄頁

To be Continue… 回目錄頁