Search code examples
c++staticdictionaryinitializationconstants

How to initialize a private static const map in C++?


I need just dictionary or associative array string => int.

There is type map C++ for this case.

But I need only one map forall instances(-> static) and this map can't be changed(-> const);

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();

};

Solution

  • #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() {
    }