Home >Backend Development >C++ >How to Initialize a Static `std::map` in C ?

How to Initialize a Static `std::map` in C ?

DDD
DDDOriginal
2024-12-09 13:04:10184browse

How to Initialize a Static `std::map` in C  ?

Initializing a Static Map in C

In C , initializing a static std::map presents a unique challenge. There is no straightforward method like using an initializer list or a static function. However, there are several approaches that offer alternative solutions.

Using C 11 Initializer List

C 11 introduces an initializer list syntax that can be utilized to initialize the map. The elements within curly braces are enclosed in pairs of curly braces, with each pair representing a key-value pair. The order of initialization is irrelevant as the map automatically sorts the elements based on their keys.

#include <map>

using namespace std;

static map<int, int> m = {{1, 2}, {3, 4}, {5, 6}};

Using Boost.Assign

Boost.Assign is a library that provides convenient macros for initializing maps and other data structures. It offers a concise syntax for specifying key-value pairs within a map.

#include <boost/assign.hpp>

using namespace std;
using namespace boost::assign;

static map<int, int> m = map_list_of(1, 2)(3, 4)(5, 6);

The above is the detailed content of How to Initialize a Static `std::map` in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn