繁体   English   中英

声明std :: map常量

[英]Declaring std::map constants

如何声明std map常量ie,

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

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

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

map<int, int> m = {{1,2}, {3,4}};

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

std::map<int, int> my_map{ {1, 5}, {2, 15}, {-3, 17} };

...或类似的,其中每对值 - 例如{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';
}

我被Boost.Assign解决了这个问题,我写了一篇关于它的博客文章大约一年半前(就在我放弃博客之前):

该帖子的相关代码是:

#include <boost/assign/list_of.hpp>
#include <map>

static std::map<int, int>  amap = boost::assign::map_list_of
    (0, 1)
    (1, 1)
    (2, 2)
    (3, 3)
    (4, 5)
    (5, 8);


int f(int x)
{
    return amap[x];
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM