C++ 声明 std::map 常量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4396808/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 15:18:29  来源:igfitidea点击:

Declaring std::map constants

c++stl

提问by Chandan Shetty SP

How to declare std map constants i.e.,

如何声明 std 映射常量,即

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

In the about snippet it is possible to give values 1,2,3,4 to integer array a, similarly how to declare some constant MapTypevalues instead of adding values inside main() function.

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

回答by Matthew Flaschen

In C++0x, it will be:

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

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

回答by Tony Delroy

UPDATE: with C++11 onwards you can...

更新:从 C++11 开始,你可以......

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

...or similar, where each pair of values - e.g. {1, 5}- encodes a key - 1- and a mapped-to value - 5. The same works for unordered_map(a hash table version) too.

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



Using just the C++03 Standard routines, consider:

仅使用 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';
}

回答by Kaz Dragon

I was so taken by the Boost.Assignsolution to this problem that I wrote a blog post about it about a year and a half ago (just before I gave up on blogging):

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

The relevant code from the post was this:

帖子中的相关代码是这样的:

#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];
}