How to Initialize a Static std::map<int, int> in C++
Last Updated :
02 Aug, 2024
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++:
- With Declaration Using Initializer List
- Using a Static Member Function
- Using a Static Initialization Block
1. Initialize with Declaration Using Initializer List
The 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:
C++
// C++ program to demonstrate initialization of a static
// std::map<int, int> using initializer list
// Include necessary header files
#include <iostream>
#include <map>
using namespace std;
// Initialize a static const map with some key-value pairs
static const map<int, int> myMap
= { { 1, 10 }, { 2, 20 }, { 3, 30 }, { 4, 40 } };
int main()
{
// Iterate through the map and print each key-value pair
for (const auto& pair : myMap) {
cout << "Key: " << pair.first
<< ", Value: " << pair.second << endl;
}
return 0;
}
OutputKey: 1, Value: 10
Key: 2, Value: 20
Key: 3, Value: 30
Key: 4, Value: 40
2. Using a Static Member Function
Another 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:
C++
// C++ program to demonstrate initialization of a static
// std::map<int, int> using static member function
// Include necessary header files
#include <iostream>
#include <map>
using namespace std;
// Class to initialize and return a static map
class MapInitializer {
public:
// Static function to return a constant reference to the
// static map
static const map<int, int>& getMap()
{
// Initialize the static map with key-value pairs
static const map<int, int> myMap = {
{ 1, 10 }, { 2, 20 }, { 3, 30 }, { 4, 40 }
};
// Return the map
return myMap;
}
};
int main()
{
// Get the static map from the MapInitializer class
const map<int, int>& myMap = MapInitializer::getMap();
// Iterate through the map and print each key-value pair
for (const auto& pair : myMap) {
cout << "Key: " << pair.first
<< ", Value: " << pair.second << endl;
}
// Return 0 to indicate successful execution
return 0;
}
OutputKey: 1, Value: 10
Key: 2, Value: 20
Key: 3, Value: 30
Key: 4, Value: 40
3. Using a Static Initialization Block
For 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:
C++
// C++ program to demonstrate initialization of a static
// std::map<int, int> using static initialization block
// Include necessary header files
#include <iostream>
#include <map>
using namespace std;
// Function to initialize and return a reference to a static
// map
static const map<int, int>& getMap()
{
// Initialize the static map
static map<int, int> myMap;
// Check if the map is empty
if (myMap.empty()) {
// Populate the map with key-value pairs
myMap[1] = 10;
myMap[2] = 20;
myMap[3] = 30;
myMap[4] = 40;
}
// Return the map
return myMap;
}
int main()
{
// Get the static map from the getMap function
const map<int, int>& myMap = getMap();
// Iterate through the map and print each key-value pair
for (const auto& pair : myMap) {
cout << "Key: " << pair.first
<< ", Value: " << pair.second << endl;
}
return 0;
}
OutputKey: 1, Value: 10
Key: 2, Value: 20
Key: 3, Value: 30
Key: 4, Value: 40
Similar Reads
Different Ways to Initialize a List in C++ STL
Initializing a list means assigning some initial values to the list elements. In this article, we will learn different methods to initialize the list in C++. Letâs start from the easiest method: The easiest way to initialize a list is by passing the initial values inside an initializer list to its c
3 min read
How to initialize Array of objects with parameterized constructors in C++
Array of Objects: When a class is defined, only the specification for the object is defined; no memory or storage is allocated. To use the data and access functions defined in the class, you need to create objects. Syntax: ClassName ObjectName[number of objects]; Different methods to initialize the
6 min read
Different Ways to Initialize a Variable in C++
Variables are arbitrary names given to the memory location in the system. These memory locations are addressed in the memory. In simple terms, the user-provided names for memory locations are called variables. Additionally, a data type is used to declare and initialize a variable. Suppose we want to
4 min read
Initialization of Multidimensional Arrays in C++
In C++, multidimensional arrays are the type of arrays that have multiple dimensions, i.e., they can expand in multiple directions. In this article, we will discuss how to initialize the multidimensional arrays in C++. Methods to Initialize Multidimensional Array in C++We can initialize multidimensi
3 min read
Searching in a map using std::map functions in C++
In C++, map container is defined as std::map class template that also contains member function to search for an element on the bases of the keys. In this article, we will learn different methods to search for an element with the given key in C++. The recommended method to search for the given key in
4 min read
When do we use Initializer List in C++?
Initializer List is used in initializing the data members of a class. The list of members to be initialized is indicated with constructor as a comma-separated list followed by a colon. Following is an example that uses the initializer list to initialize x and y of Point class. Example [GFGTABS] C++
8 min read
7 ways to Initialize Vector in C++
Initializing a vector means assigning some initial values to the std::vector elements. In this article, we will learn 8 different ways to initialize a vector in C++. Table of Content Using Initializer ListOne by One InitializationWith a Single ValueFrom an ArrayFrom Another VectorFrom Any STL Contai
5 min read
Map of list and forward_list in C++ STL with Examples
Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have the same key values. Lists are sequence containers that allow non-contiguous memory allocation. As compared to vector, the list has slow traversal,
5 min read
Map and External Sorting Criteria/Comparator in C++ STL
C++ Map is another commonly used STL container, it stores elements in a mapped fashion. Each element is stored as a pair having a key value and a mapped value. No two mapped values can have the same key values which means each key is unique. By default, key values in the map are in lexicographically
4 min read
Some interesting facts about static member functions in C++
1) static member functions do not have this pointer. For example following program fails in compilation with error "`this' is unavailable for static member functions " C/C++ Code #include<iostream> class Test { static Test * fun() { return this; // compiler error } }; int main() { getchar(); r
1 min read