1. 程式人生 > >C++:C++標準庫中的關聯式容器Map

C++: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;
}

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