C++:關聯式容器Map

Map每個元素都是 key/value pair ,其中key是排序準則的基準。每個key只能出現一次,不允許重複。Map
也可被視爲一種關聯式數組,也就是“索引可爲任意類型”的數組。
以具體的兩個例子解釋什麼是map

實例一

#include "pch.h"
#include <map>
#include <iostream>
#include <string>
using namespace std;
int main()
{
    map<int, string> coll;
    coll = { {5, "tagged"},
        {2, "a"},
        {1, "this"},
        {4, "of"},
        {6, "strings"},
        {1, "is"},
        {3, "map"}
    };
    for (auto elem : coll) {
        cout << elem.second << ' ';
    }
    cout << endl;
    getchar();
}

輸出結果是
在這裏插入圖片描述

實例二

#include "pch.h"
#include <map>
#include <iostream>
#include <string>
using namespace std;
int main ()
{
    int a[5];
    map<int, int>M;
    a[0] = 1; M[a[0]]++;
    a[1] = 2; M[a[1]]++;
    a[2] = 2; M[a[2]]++;
    a[3] = 4; M[a[3]]++;
    a[4] = 1; M[a[4]]++;
    map<int, int>::iterator it;
    for (it = M.begin(); it != M.end(); it++)
        cout << it->first << ' ' << it->second << endl;
    getchar();
    return 0;
}

輸出結果是
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章