Home >Backend Development >C++ >How to Effectively Initialize a Static `std::map` in C ?
Initializing Static std::map
When working with static maps in C , one may wonder about the proper method for initialization. This question delves into the available options for initializing a static map effectively.
C 11 Initializer List
One approach is to utilize C 11 initializer lists. These lists enable the specification of initial values within curly braces, preserving the order of insertion. The map automatically sorts elements based on their keys.
#include <map> using namespace std; map<int, char> m = {{1, 'a'}, {3, 'b'}, {5, 'c'}, {7, 'd'}};
Boost.Assign Library
Alternatively, you can employ the Boost.Assign library, which provides the map_list_of macro. This macro facilitates the initialization of maps with key-value pairs in a concise syntax:
#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');
By leveraging the initializer list or Boost.Assign library, you can effortlessly initialize static maps in C , creating a convenient and efficient approach.
The above is the detailed content of How to Effectively Initialize a Static `std::map` in C ?. For more information, please follow other related articles on the PHP Chinese website!