What is the right way of initializing a static map? Do we need a static function that will initialize it?
Originally Answered: How do you initialize a static std: :map<int, int> in C++? At file scope, you use list initialization or an expression which may invoke a lambda. In a class you wrap it in a static function to work around object initialization order being undefined across multiple compilation units.
Initialize a std::map or std::unordered_map in C++ 1. Using Initializer List. In C++11 and above, we can use the initializer lists ' {...}' to initialize a map container. 2. From array of pairs. We can use a range constructor to initialize the set from elements of an array of pairs or... 3. From ...
This post will discuss how to initialize a map in C++. There are several approaches to initialize a std::mapor std::unordered_mapin C++, as shown below: 1. Using Initializer List In C++11 and above, we can use the initializer lists'{...}'to initialize a map container.
The simplest answer of to why there is no standard way to initialise a static map, is there is no good reason to ever use a static map... A map is a structure designed for fast lookup, of an unknown set of elements.
Using C++11:
#include <map> using namespace std; map<int, char> m = {{1, 'a'}, {3, 'b'}, {5, 'c'}, {7, 'd'}};
Using Boost.Assign:
#include <map> #include "boost/assign.hpp" using namespace std; using namespace boost::assign; map<int, char> m = map_list_of (1, 'a') (3, 'b') (5, 'c') (7, 'd');
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