如何声明std映射常量,即,
int a[10] = { 1, 2, 3 ,4 };
std::map <int, int> MapType[5] = { };
int main()
{
}在about片段中,可以将值1,2,3,4给整数数组一个,类似地,如何声明一些常量MapType值,而不是在main()函数中添加值。
发布于 2010-12-09 10:08:49
更新:随着C++11的开始,你可以.
std::map<int, int> my_map{ {1, 5}, {2, 15}, {-3, 17} };...or类似,其中每一对值--例如,{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';
}发布于 2010-12-09 09:55:01
在C++0x中,它将是:
map<int, int> m = {{1,2}, {3,4}};发布于 2010-12-09 09:59:12
对于这个问题,我被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];
}https://stackoverflow.com/questions/4396808
复制相似问题