![]() |
In C++, std::map<int, int> is a commonly used container that stores key-value pairs. There are scenarios where we may want to initialize a static std::map with predefined key-value pairs that remain constant throughout the program’s execution. In this article, we will learn different methods to initialize a static std::map<int, int> in C++. Initialize std::map<int, int> in C++There are mainly three ways to initialize a static std::map<int, int> in C++:
1. Initialize with Declaration Using Initializer ListThe simplest way to initialize a static std::map<int, int> is at the time of declaration by using an initializer list introduced in C++ 11 . Syntax: static const std::map<int, int> myMap = {
{key1, value1},
{key2, value2},
...
{keyN, valueN}
}; Example:
Output Key: 1, Value: 10 Key: 2, Value: 20 Key: 3, Value: 30 Key: 4, Value: 40 2. Using a Static Member FunctionAnother method is to use a static member function that returns a pre-initialized std::map. This approach is useful when dealing with complex initialization logic. Syntax: class MapInitializer {
public:
static const std::map<int, int>& getMap() {
static const std::map<int, int> myMap = {
{key1, value1},
{key2, value2},
...
{keyN, valueN}
};
return myMap;
}
}; Example:
Output Key: 1, Value: 10 Key: 2, Value: 20 Key: 3, Value: 30 Key: 4, Value: 40 3. Using a Static Initialization BlockFor older versions of C++ that do not support initializer lists, we can use a static initialization block within a function. Syntax: static const std::map<int, int>& getMap() {
static std::map<int, int> myMap;
if (myMap.empty()) {
myMap[key1] = value1;
myMap[key2] = value2;
...
myMap[keyN] = valueN;
}
return myMap;
} Example:
Output Key: 1, Value: 10 Key: 2, Value: 20 Key: 3, Value: 30 Key: 4, Value: 40 |
Reffered: https://www.geeksforgeeks.org
C++ |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 20 |