How to Store Multiple Values for the Same Key in C++?

In C++ STL, maps are used to store key-value pairs but they only allow one value for a key. Sometimes, we might want multiple values to be associated with a single key. In this article, we will learn how to store multiple values for the same key in C++.

Example:

Input:
Key:1; Value:Red
Key:1; Value:Blue
Key:1; Value:Green
Key:2; Value:Apple
Key:2; Value:Mango
Key:2; Value:Banana

Output:
Key: 1, Values: Red Blue Green
Key: 2, Values: Apple Mango Banana

Multiple Values for the Same Key in C++

In C++, if we want to associate multiple values with the same key, we can use std::multimap that allows us to store multiple elements that have the same key and also permits the storage of duplicate keys for the same value. To insert elements into the multimap, use the std::multimap::insert() function.

C++ Program to Use Multiple Values for the Same Key

The below program demonstrates how we can use multiple values for the same key in C++.

C++
// C++ Program to illustrate how to use multiple values for
// the same key
#include <iostream>
#include <map>
using namespace std;

int main()
{
    // Declaration of the multimap
    multimap<int, string> mm;

    // Inserting keys and their respective values into the
    // multimap
    mm.insert({ 1, "Red" });
    mm.insert({ 1, "Blue" });
    mm.insert({ 1, "Green" });
    mm.insert({ 2, "Apple" });
    mm.insert({ 2, "Mango" });
    mm.insert({ 2, "Banana" });

    // Printing the keys and their respective values
    cout << "Multimap: " << endl;
    auto it = mm.begin();
    while (it != mm.end()) {
        int key = it->first;
        cout << "Key: " << key << ", Values: ";
        while (it != mm.end() && it->first == key) {
            cout << it->second << " ";
            it++;
        }
        cout << endl;
    }

    return 0;
}

Output
Multimap: 
Key: 1, Values: Red Blue Green 
Key: 2, Values: Apple Mango Banana 

Time Complexity: O(log n), here n is the number of elements in the multimap.
Auxilliary Space : O(n)


Contact Us