首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >声明std::map常量

问声明std::map常量
EN

Stack Overflow用户
提问于 2010-12-09 09:47:55
回答 3查看 26.4K关注 0票数 5

如何声明std映射常量,即,

代码语言:javascript
复制
int a[10] = { 1, 2, 3 ,4 };
std::map <int, int> MapType[5] = { };
int main()
{
}

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

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2010-12-09 10:08:49

更新:随着C++11的开始,你可以.

代码语言:javascript
复制
std::map<int, int> my_map{ {1, 5}, {2, 15}, {-3, 17} };

...or类似,其中每一对值--例如,{1, 5} --编码一个键-- 1 --和映射到-- 5。unordered_map (哈希表版本)也是如此。

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

代码语言:javascript
复制
#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';
}
票数 12
EN

Stack Overflow用户

发布于 2010-12-09 09:55:01

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

代码语言:javascript
复制
map<int, int> m = {{1,2}, {3,4}};
票数 7
EN

Stack Overflow用户

发布于 2010-12-09 09:59:12

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

该职位的相关代码如下:

代码语言:javascript
复制
#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];
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4396808

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档