声明std :: map常量

Cha*_* SP 3 c++ stl

如何声明std map常量ie,

int a[10] = { 1, 2, 3 ,4 };
std::map <int, int> MapType[5] = { };
int main()
{
}
Run Code Online (Sandbox Code Playgroud)

在about片段中,可以给整数数组a赋值1,2,3,4 ,类似地如何声明一些常量MapType值而不是在main()函数中添加值.

Mat*_*hen 6

在C++ 0x中,它将是:

map<int, int> m = {{1,2}, {3,4}};
Run Code Online (Sandbox Code Playgroud)


Ton*_*roy 5

更新:使用C++ 11以后你可以......

std::map<int, int> my_map{ {1, 5}, {2, 15}, {-3, 17} };
Run Code Online (Sandbox Code Playgroud)

......或类似的,其中每对值 - 例如{1, 5}- 编码一个键1- 和一个映射到的值 - 5.同样适用于unordered_map(哈希表版本).


仅使用C++ 03标准例程,请考虑:

#include <iostream>
#include <map>

typedef std::map<int, std::string> Map;

const Map::value_type x[] = { std::make_pair(3, "three"),
                              std::make_pair(6, "six"),
                              std::make_pair(-2, "minus two"), 
                              std::make_pair(4, "four") };

const Map m(x, x + sizeof x / sizeof x[0]);

int main()
{
    // print it out to show it works...
    for (Map::const_iterator i = m.begin();
            i != m.end(); ++i)
        std::cout << i->first << " -> " << i->second << '\n';
}
Run Code Online (Sandbox Code Playgroud)