Initializing a Static std::map
When dealing with static maps in C , the question arises as to how to initialize them appropriately.
To initialize a static map, one possible approach is to employ a static function that handles the initialization process. However, there is a more convenient and modern method available thanks to C 11.
Using C 11's initializer list syntax, you can initialize a static map as follows:
#include <map> using namespace std; static std::map<int, int> myMap = {{1, 2}, {3, 4}, {5, 6}};
The order of elements in the initializer list is irrelevant as the map will automatically sort the elements by their keys. This approach allows for easy and concise initialization of static maps.
Alternatively, you can leverage the Boost.Assign library to initialize static maps, providing another convenient option.
For example, with Boost.Assign:
#include <map> #include "boost/assign.hpp" using namespace std; using namespace boost::assign; static std::map<int, int> myMap = map_list_of(1, 2)(3, 4)(5, 6);
Both of these methods offer efficient and straightforward mechanisms for initializing static maps in C .
The above is the detailed content of How Can I Efficiently Initialize a Static `std::map` in C ?. For more information, please follow other related articles on the PHP Chinese website!