C++ 入門指南 4.01

練習 19.5 參考程式 - 練習標準程式庫的 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> m1 = {
        {"Mary", 70},
        {"John", 80},
    };

    // 宣告建立字串、整數 map
    map<string, int> m2 = {
        {"Tony", 90},
        {"Alice", 100}
    };

    // 兩個 map 交換內容
    m1.swap(m2);

    // 印出 m1 的元素內容
    for (auto e: m1) {
        cout << e.first << ':' << e.second << ' ';
        cout << endl;
    }

    // 最後回傳 0 給作業系統
    return 0;
}

/* 《程式語言教學誌》的範例程式
   http://kaiching.org/
   檔名:exercise1905.cxx
   編譯:g++ exercise1905.cxx -std=c++11
   執行:./a.out
   功能:C++入門指南單元十九的練習
   作者:張凱慶 */
回到練習題目

上一頁 練習 19.4 參考程式 - 練習標準程式庫的 map
回 C++ 入門指南 4.01 目錄
下一頁 練習 19.6 參考程式 - 練習標準程式庫的 printf()
回 C++ 教材
回程式語言教材首頁