VOOZH about

URL: https://www.geeksforgeeks.org/cpp/best-way-to-map-multiple-vectors-to-keys-in-a-multimap-in-cpp/

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


  • Courses
  • Tutorials
  • Interview Prep

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

Last Updated : 23 Jul, 2025

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

  • First, initialize a multimap where the type of the values is vectors.
  • Create a mapping of vectors and their corresponding keys using the std::make_pair() function.
  • Insert the pairs into the multimap using the std::multimap::insert() function.

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++:


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.



Comment