How to Create a Multimap of Vectors in C++?
Last Updated :
27 Feb, 2024
In C++, a multimap is similar to a map with the addition that multiple elements can have the same keys. Also, it is not required that the key-value and mapped value pair have to be unique in this case. In this article, we will learn how to create a multimap of vectors in C++.
For Example,
Input:
myPair1 = {1, {2, 3, 4}}
myPair2 = {2, {5, 6, 7}}
Output:
MultiMap = { {1, {2, 3, 4}}, {2, {5, 6, 7}} }
Creating a Multimap of Vectors in C++
To create a multimap of vectors, we will have to first declare a multimap where in each key-value pair, the key is of type string and the value is a vector.
We can then use the std::multimap::insert() function to insert key-value pairs into the multimap. The key is a string, and the value is a vector.
Syntax to Create a Multimap of Vectors
multimap<string, vector<int> > myMultimap;
C++ Program to Create a Multimap of Vectors
C++
#include <iostream>
#include <map>
#include <vector>
using namespace std;
int main()
{
multimap<string, vector< int > > myMultimap;
myMultimap.insert({ "apple" , { 1, 2 } });
myMultimap.insert({ "banana" , { 2, 3, 4 } });
myMultimap.insert({ "cherry" , { 3, 4, 5, 6 } });
myMultimap.insert({ "apple" , { 1, 2 } });
for ( auto it = myMultimap.begin();
it != myMultimap.end(); ++it) {
cout << it->first << " " ;
for ( auto vec_it = it->second.begin();
vec_it != it->second.end(); ++vec_it) {
cout << *vec_it << " " ;
}
cout << endl;
}
return 0;
}
|
Output
apple 1 2
apple 1 2
banana 2 3 4
cherry 3 4 5 6
Time Complexity: O(N * log N), where N is the number of arrays.
Space Complexity: O(N * M), where M is the average size of the arrays.
Share your thoughts in the comments
Please Login to comment...