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_
?
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.
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.
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.
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"); }};
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With