Take user input in map in C++

In this tutorial, we will learn how to take input from the user in a map in C++.

Maps in C++ are container structures that store elements in key-value pairs. For every unique key, there is a data value mapped to it, that can be easily accessed if we know the key. Every key has to be unique, and no two keys can be the same(but the values associated with keys can be the same).

To declare a map in C++, we use the following syntax:

map <key_dataType, value_dataType> mapName;

Here, the key_dataType is the data type of the key, the value_dataType is the data type of the value, mapName is the name of the map.

Inserting data in maps

The map::insert() is a built-in function that is used to insert elements with a particular key in the map container.

The following code will explain how we can insert data into the map:

#include <bits/stdc++.h>
using namespace std;
  
int main()
{
    map<int, int> m1;         //creating map
  
    m1.insert({ 2, 20 });     // inserting elements in random order
    m1.insert({ 1, 10 });
    m1.insert({ 3, 30 });
    m1.insert({ 4, 40 });
    m1.insert({ 5, 50 });
  

  
    // prints the elements
    cout << "KEY\tELEMENT\n";
    for (auto itr = m1.begin(); itr != m1.end(); ++itr) {
        cout << itr->first
             << '\t' << itr->second << '\n';
    }
    return 0;
}
Output:

KEY ELEMENT
1 10
2 20
3 30
4 40
5 50

Here in this code, we have inserted the data using the insert function. Keyword auto and the iterator itr is used to traverse through the map and print the keys and respective elements.

Taking user input in a map in C++

Here we have given the input but we can also make the code such that the user can enter the data.

The following program illustrates this:

#include<iostream>
#include<map>
using namespace std;
int main()
{
    map<int,int>m1;
    int n,a,b;
    cout<<"Enter the number of elements you want to enter"<<endl;
    cin>>n;
    cout<<"Enter the elements"<<endl;
    for(int i = 0; i<n; i++){
        cin>>a>>b;
        m1.insert(pair<int,int>(a,b));
    }
    cout<<endl;
    cout<<"The elements are"<<endl;
    for(auto&x:m1)
    {
        cout<<x.first<<":"<<x.second<<endl;
    }
    return 0;
}
Output:

Enter the number of elements you want to enter
5
Enter the elements
1 10
2 20
3 30
4 40
5 50

The elements are
1:10
2:20
3:30
4:40
5:50

Thus using the for loop and the insert function we can take the input from the user.

Leave a Reply

Your email address will not be published. Required fields are marked *