C++ 入門指南 4.01
練習 19.4 參考程式 - 練習標準程式庫的 map
// 引入標準程式庫中相關的輸入、輸出程式
#include <iostream>
// 引入標準程式庫中的 map
#include <map>
// 引入標準程式庫中相關的 string
#include <string>
// cout 為 std 中的輸出物件
using std::cout;
// endl 為 std 中的斷行符號
using std::endl;
// string 為 std 中的字串型態
using std::string;
// map 為 std 中的集合體型態
using std::map;
int main(void) {
// 宣告建立字串、整數 map
map<string, int> m = {
{"Mary", 70},
{"John", 80},
{"Tony", 90},
{"Alice", 100}
};
// 移除 "Mary"
for(auto it = m.begin(); it != m.end(); ) {
if (it->first == "Mary") {
it = m.erase(it);
}
else {
++it;
}
}
// 印出 map 的元素內容
for (auto e: m) {
cout << e.first << ':' << e.second << ' ';
cout << endl;
}
// 最後回傳 0 給作業系統
return 0;
}
/* 《程式語言教學誌》的範例程式
http://kaiching.org/
檔名:exercise1904.cxx
編譯:g++ exercise1904.cxx -std=c++11
執行:./a.out
功能:C++入門指南單元十九的練習
作者:張凱慶 */
回到練習題目