C++ 声明std::map常量
如何声明std映射常量,即C++ 声明std::map常量,c++,stl,C++,Stl,如何声明std映射常量,即 int a[10] = { 1, 2, 3 ,4 }; std::map <int, int> MapType[5] = { }; int main() { } inta[10]={1,2,3,4}; std::map MapType[5]={}; int main() { } 在about代码段中,可以为整数数组a指定值1、2、3、4,类似地,如何声明一些常量MapType值,而不是在main()函数中添加值。在C++0x中,它将是: map<
int a[10] = { 1, 2, 3 ,4 };
std::map <int, int> MapType[5] = { };
int main()
{
}
inta[10]={1,2,3,4};
std::map MapType[5]={};
int main()
{
}
在about代码段中,可以为整数数组a指定值1、2、3、4,类似地,如何声明一些常量MapType值,而不是在main()函数中添加值。在C++0x中,它将是:
map<int, int> m = {{1,2}, {3,4}};
map m={{1,2},{3,4};
我被这个问题的解决方案吸引住了,大约一年半前(就在我放弃写博客之前)我写了一篇关于这个问题的博文:
该职位的相关代码如下:
#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];
}
#包括
#包括
静态std::map amap=boost::assign::map\u列表
(0, 1)
(1, 1)
(2, 2)
(3, 3)
(4, 5)
(5, 8);
整数f(整数x)
{
返回amap[x];
}
更新:使用C++11以后的版本,您可以
std::map<int, int> my_map{ {1, 5}, {2, 15}, {-3, 17} };
您意识到您声明了一个由5个
std::map
组成的数组?@Fritschy:这样,您可以在每个map中拥有更少的元素,并且查找速度会更快…;-)@托尼,我没有那样想,说得好;)
#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';
}