The Wayback Machine - https://web.archive.org/web/20250114165425/https://www.geeksforgeeks.org/different-ways-to-initialize-a-map-in-cpp/
Open In App

Different Ways to Initialize a Map in C++

Last Updated : 08 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Initializing map refers to the process of assigning the initial values to the elements of map container. In this article, we will learn different methods to initialize the map in C++. Let’s start from the easiest method:

Using Initializer List

The simplest way to initialize an std::map container is by passing the key-value pairs inside an initializer list to its constructor.

Syntax

map<ktype, vtype> m = { {k1, v1}, {k2, v2}, …}

where, k1, k2,… are the keys and v1, v2,… are the associated values.

C++
#include <bits/stdc++.h>
using namespace std;

int main() {

    // Inializing std::map using initializer list
    map<int, char> m = {{1, 'a'},
                        {3, 'b'},
                        {2, 'c'}};

    for (auto i : m)
        cout << i.first << ": " << i.second << endl;
    return 0;
}

Output
1: a
2: c
3: b

Explanation: The key-value pairs specified in the initializer list are used as initial value of map elements. These elements are then organized on the basis of keys.

Apart from the above method, C++ also provides other different methods to initialize a map depending on the situation. Some of them are:

Using One by One Initialization

Map can be initialized by initializing all elements one by one using [] operator or by using the map insert() method.

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    map<int, char> m;

    // Adding key-value pairs using [] or map::insert()
    m[1] = 'a';
    m[3] = 'b';
    m.insert({2, 'c'});

    for (auto i : m)
        cout << i.first << ": " << i.second << endl;
    return 0;
}

Output
1: a
2: c
3: b

This method is generally used to initialize map after its declaration.

From Another Map

Maps can be initialized from an already existing map of the same type by copying all elements with the help of copy constructor.

Syntax

map<ktype, vtype> m2(m1);

where, m1 and m2 are the two map containers.

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    map<int, char> m1 = {{1, 'a'},
                         {3, 'b'},
                         {2, 'c'}};

    //Create and initialize the map m2 with map m1
    map<int, char> m2(m1);

    for (auto i : m2)
        cout << i.first << ": " << i.second << endl;
    return 0;
}

Output
1: a
2: c
3: b

We can also move the map using std::move() function if we don’t need the first map later in the program.

From Any STL Container or Array of Pairs

The map range constructor can initialize a map from any other STL container or an array of pairs.

Syntax

map<int, char> m(first, last);

where, first and last are the iterator to the first element and the element just after the last element of the range.

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<pair<int, char>> v = {{1, 'a'},
                                 {3, 'b'}, 
                                 {2, 'c'}};

    // Create and initialize the map with vector
    map<int, char> m(v.begin(), v.end());

    for (auto i : m)
        cout << i.first << ": " << i.second << endl;
    return 0;
}

Output
1: a
2: c
3: b

Note: The other container or array of pairs must be of the same type as ours map.

C++ Map Initialization – FAQs

Can we use initializer list to initialize map after declaration?

Yes, we can use initializer list to initialize map after declaration.

What happens if duplicate keys are added during initialization?

Only the last value for a given key is stored, as keys in a map are unique.

Can you initialize a map with keys-value pairs of different types?

No, the types should be same as in the map declaration.


Master C++ with our comprehensive C++ Programming Course Online, perfect for anyone from beginners to advanced learners. Learn everything from the fundamentals to advanced C++ concepts, and apply your knowledge through practical exercises.

Take the Three 90 Challenge! Finish 90% of the course in 90 days, and enjoy a 90% refund. Stay focused, track your progress, and challenge yourself to complete the course! Join today and begin your C++ programming journey!


Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg