Open In App

What’s the Best Way to Map Multiple Vectors to Keys in a Multimap in C++?

In C++, multimaps are associative containers in which multiple values can be stored corresponding to the same key and vectors are dynamic arrays that store data in contiguous memory locations. In this article, we will learn what's the best way to map multiple vectors to keys in a multimap in C++.

Example:

Input:
Vec1 = {1,2,3}
Vec2 = {4,5,6}
Vec3 = {7,8,9}

Output:
Multimap Elements:
1 --->{1,2,3}
1--->{7,8,9}
2--->{4,5,6}

Mapping Multiple Vectors to the Same Key in a Multimap

To map multiple std::vectors to keys in a std::multimap, the best way is to use the multimap::insert() function and make_pair() function to efficiently make and insert vector with their keys in the multimap. We can follow the below approach to map multiple vectors to keys in a multimap:

Approach

C++ Program to Map Multiple Vectors to Keys in a Multimap

The following program illustrates how we can map multiple vectors to keys in a multimap in C++:

// C++ Program to map multiple vectors to keys in a multimap
#include <iostream>
#include <map>
#include <vector>
using namespace std;

int main()
{
    // Initialize a multimap
    multimap<int, vector<int> > mp;

    // Declare the vectors you want to map in the multimap
    vector<int> vec1 = { 1, 2, 3 };
    vector<int> vec2 = { 4, 5, 6 };
    vector<int> vec3 = { 7, 8, 9 };

    // Insert the vectors into the multimap by mapping them
    // to the keys
    mp.insert(make_pair(1, vec1));
    mp.insert(make_pair(1, vec3));
    mp.insert(make_pair(2, vec1));

    // Print the entires in the multimap
    cout << "Elements in Multimaps are:" << endl;
    for (auto pair : mp) {
        cout << "Key: " << pair.first << ", Value: ";
        for (auto element : pair.second) {
            cout << element << " ";
        }
        cout << endl;
    }
    return 0;
}

Output
Elements in Multimaps are:
Key: 1, Value: 1 2 3 
Key: 1, Value: 7 8 9 
Key: 2, Value: 1 2 3 

Time Complexity O(N log N), here N is the number of vectors.
Auxiliary Space: O(N * M), here M is the average number of elements in each vector.



Article Tags :