Open In App

Aggregate Multimap Values with Same Key and Store in Map in C++

Last Updated : 20 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, a multimap is an associative container that contains a sorted list of key-value pairs, while the same key can contain multiple values. It is a version of a map that allows duplicate keys. In this article, we will learn how to aggregate multimap values with the same key and store them in a map using C++.

Example:

Input: 
myMultimap = { {“apple”, 1}, {“banana”, 2},
              {“apple”, 3}, {“banana”, 4},
              {“apple”, 5}, {“banana”, 6} }

Output: 
myMap = {“apple”: [1, 3, 5], “banana”: [2, 4, 6]}

Aggregate Keys of Map in Vector

For aggregating the values associated with a single key in the std::multimap and storing it in the map with the corresponding key, we can use the vector to store multiple values of the key as the value type for the map container. We can then insert the key-value pairs using the [] operators.

C++ Program to Aggregate Multimap Keys in a Vector

The below example demonstrates how we can aggregate multimap keys in a vector in C++.

C++
// C++ program to aggregate multimap values with the same
// key and store them in a map

#include <iostream>
#include <map>
#include <vector>
using namespace std;

int main()
{
    // Multimap and map to be used
    multimap<string, int> myMultimap
        = { { "apple", 1 }, { "banana", 2 },
            { "apple", 3 }, { "banana", 4 },
            { "apple", 5 }, { "banana", 6 } };
    map<string, vector<int> > myMap;

    // Aggregate multimap values with the same key
    for (auto& kv : myMultimap) {
        myMap[kv.first].push_back(kv.second);
    }

    // Print the map after aggregation
    cout << "Map after aggregation: " << endl;
    for (auto& kv : myMap) {
        cout << kv.first << ": ";
        for (int val : kv.second) {
            cout << val << " ";
        }
        cout << endl;
    }

    return 0;
}

Output
Aggregated keys in the vector: 1 1 2 2 3 

Time Complexity: O(N)
Auxilliary Space: O(N)


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads