如何在C ++中初始化私有静态const映射? [英] How to initialize a private static const map in C++?
本文介绍了如何在C ++中初始化私有静态const映射?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我只需要字典或关联数组 string
=> int
。
I need just dictionary or associative array string
=> int
.
这种情况下有类型映射C ++。
There is type map C++ for this case.
但是我只需要一个映射forall实例( - > static),这个映射不能改变( - > const);
But I need only one map forall instances(-> static) and this map can't be changed(-> const);
我用boost库找到了这个方法
I have found this way with boost library
std::map<int, char> example =
boost::assign::map_list_of(1, 'a') (2, 'b') (3, 'c');
有没有这个lib的其他解决方案?
我试过这样的东西,但是地图初始化总是有一些问题。
Is there other solution without this lib? I have tried something like this, but there are always some issues with map initialization.
class myClass{
private:
static map<int,int> create_map()
{
map<int,int> m;
m[1] = 2;
m[3] = 4;
m[5] = 6;
return m;
}
static map<int,int> myMap = create_map();
};
推荐答案
#include <map>
using namespace std;
struct A{
static map<int,int> create_map()
{
map<int,int> m;
m[1] = 2;
m[3] = 4;
m[5] = 6;
return m;
}
static const map<int,int> myMap;
};
const map<int,int> A:: myMap = A::create_map();
int main() {
}
这篇关于如何在C ++中初始化私有静态const映射?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文