How to initialize a private static const map in C++?(如何在 C++ 中初始化私有静态常量映射?)
问题描述
我只需要字典或关联数组 string => int.
I need just dictionary or associative array string => int.
这种情况下有类型映射 C++.
There is type map C++ for this case.
但我只需要一张地图用于所有实例(-> 静态),而这张地图无法更改(-> 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');
没有这个库还有其他解决方案吗?我试过这样的事情,但地图初始化总是有一些问题.
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++ 中初始化私有静态常量映射?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 C++ 中初始化私有静态常量映射?
				
        
 
            
        基础教程推荐
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
 - 在 C++ 中计算滚动/移动平均值 2021-01-01
 - C++结构和函数声明。为什么它不能编译? 2022-11-07
 - 如何通过C程序打开命令提示符Cmd 2022-12-09
 - 如何检查GTK+3.0中的小部件类型? 2022-11-30
 - 如何在 C++ 中初始化静态常量成员? 2022-01-01
 - 常量变量在标题中不起作用 2021-01-01
 - 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
 - 我有静态或动态 boost 库吗? 2021-01-01
 - 这个宏可以转换成函数吗? 2022-01-01
 
    	
    	
    	
    	
    	
    	
    	
    	
						
						
						
						
						
				
				
				
				