Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing a static std::map<int, int> in C++

Tags:

c++

stl

stdmap

What is the right way of initializing a static map? Do we need a static function that will initialize it?

like image 608
Nithin Avatar asked Sep 26 '08 10:09

Nithin


People also ask

How do you initialize a static STD class in C++?

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.

How to initialize a std::map or std::unordered_map in C++?

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 ...

How to initialize a map in C++?

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.

Why is there no standard way to initialise a static map?

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.


1 Answers

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'); 
like image 89
Ferruccio Avatar answered Sep 26 '22 19:09

Ferruccio