Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static map initialization

Tags:

I have the following code:

//MyClass.h class MyClass { public:     typedef std::map<std::string, int> OpMap;     static OpMap opMap_;          // (more methods) };  //MyClass.cpp //Init opMap_ MyClass::opMap_["x"] = 1; //compilation error 

How can I (statically) initialize opMap_?

like image 684
Yakov Avatar asked Nov 19 '12 23:11

Yakov


People also ask

What is static initialization?

A Static Initialization Block in Java is a block that runs before the main( ) method in Java. Java does not care if this block is written after the main( ) method or before the main( ) method, it will be executed before the main method( ) regardless.

What is static map in Java?

In this article, a static map is created and initialized in Java. A static map is a map which is defined as static. It means that the map becomes a class member and can be easily used using class.

How do I create a static map in Java 8?

We can use Java 8 Stream to construct static maps by obtaining stream from static factory methods like Stream. of() or Arrays. stream() and accumulating the input elements into a new map using collectors.

How do you initialize a map?

The Static Initializer for a Static HashMap We can also initialize the map using the double-brace syntax: Map<String, String> doubleBraceMap = new HashMap<String, String>() {{ put("key1", "value1"); put("key2", "value2"); }};


1 Answers

If you're using C++11, you could use initializer lists:

//MyClass.h class MyClass { public:       typedef std::map<std::string, int> OpMap;       static OpMap opMap_; };  //MyClass.cpp MyClass::OpMap MyClass::opMap_ = {      { "x", 1 } };  

If you don't have access to a compiler that supports the C++11 standard, you could do the following:

//MyClass.h class MyClass { public:       typedef std::map<std::string, int> OpMap;       static OpMap opMap_; private:       static OpMap init_map() {           OpMap some_map;           some_map["x"] = 1;           return some_map;       } };  //MyClass.cpp MyClass::OpMap MyClass::opMap_ = init_map(); 
like image 109
mfontanini Avatar answered Sep 22 '22 12:09

mfontanini