Map (Key-Value Pairs)

Map (Key-Value Pairs)

Medium C++ STL 35 views
Explanation Complexity

Problem Statement

Store data in key-value pairs like dictionary.
Real Life: Phone book - name (key) to number (value).

Input Format

An integer n (number of entries)
Then n pairs:
key value

Output Format

All key–value pairs printed.

Example

3
Rahul 9876
Amit 9123
Neha 9988
Amit 9123
Neha 9988
Rahul 9876

Constraints

• Keys must be unique

• Values can repeat

• Stored in sorted order by key

Concept Explanation

A map stores data in key–value pairs, just like a dictionary.
Each key is linked to exactly one value.
Example:

• Phone book → Name (key) → Phone number (value)

Step-by-Step Explanation

1.Create a map.

2.Take input key and value.

3.Insert pair into map using map[key] = value.

4.If key already exists:

• Old value is replaced by new value.

5.Map automatically stores data sorted by key.

6.Traverse the map using loop.

7.Print each key with its value.

Concept Explanation

A map stores data in key–value pairs, just like a dictionary.
Each key is linked to exactly one value.
Example:

• Phone book → Name (key) → Phone number (value)

Step-by-Step Explanation

1.Create a map.

2.Take input key and value.

3.Insert pair into map using map[key] = value.

4.If key already exists:

• Old value is replaced by new value.

5.Map automatically stores data sorted by key.

6.Traverse the map using loop.

7.Print each key with its value.

Input / Output Format

Input Format
An integer n (number of entries)
Then n pairs:
key value
Output Format
All key–value pairs printed.
Constraints
• Keys must be unique

• Values can repeat

• Stored in sorted order by key

Examples

Input:
3 Rahul 9876 Amit 9123 Neha 9988
Output:
Amit 9123 Neha 9988 Rahul 9876

Example Solution (Public)

C++
void stl_q6_map() {
    map<string, int> ages;
    
    // Insert key-value pairs
    ages["Raj"] = 20;
    ages["Priya"] = 22;
    ages["Amit"] = 21;
    
    cout << "Raj's age: " << ages["Raj"] << endl;
    
    // Iterate
    cout << "All ages:" << endl;
    for(auto pair : ages) {
        cout << pair.first << " : " << pair.second << endl;
    }
}

Official Solution Code

void stl_q6_map() {
    map<string, int> ages;
    
    // Insert key-value pairs
    ages["Raj"] = 20;
    ages["Priya"] = 22;
    ages["Amit"] = 21;
    
    cout << "Raj's age: " << ages["Raj"] << endl;
    
    // Iterate
    cout << "All ages:" << endl;
    for(auto pair : ages) {
        cout << pair.first << " : " << pair.second << endl;
    }
}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.