How to Store Vectors as Keys in a Multimap in C++?
In C++, the std::multimap is a container that stores elements in a key-value pair, whereas std::vector is a sequence container that stores elements in contiguous memory. In this article, we will learn how to store vectors as keys in a multimap in C++.
Example:
Input:
myVector ={1,2,3};
myVector ={4,5,6};
Output:
myMultimapOfVectors = { {{1, 2, 3}, “first”},
{{4, 5, 6}, “second”},
{{7, 8, 9}, “third”} }
Store Vectors as Keys in a Multimap in C++
To store vectors as keys in a multimap in C++, we can define the type of std::multimap container keys as vector type during the declaration of the multimap. The below syntax shows how to do it.
Syntax to Declare Multimap with Vectors as Keys in C++
multimap< vector<dataType>, valueType> multimap_name;
Here,
datatype
denotes the type of data you want to store in the vector.mapped_datatype
denotes the type of data you want to store as the mapped value in the multimap.multimap_name
is the name of the multimap.
We can then use the multimap::insert or array subscript operator to insert data into the multimap.
Note: The multimap in C++ is implemented as Red-Black Trees and can work on data types that have valid <, >, == operators. So vectors can be stored as keys in it. While unordered_maps may requre a custom hash function to work on vectors.
C++ Program to Store Vectors as Keys in a Multimap
The below program demonstrates how we can store vectors as keys in a multimap in C++ STL.
// C++ Program to illustrate how to store vectors as keys in
// a multimap
#include <iostream>
#include <map>
#include <vector>
using namespace std;
int main()
{
// Define the type of vector
typedef vector<int> VectorType;
// Initialize two vectors
VectorType vec1 = { 1, 2, 3 };
VectorType vec2 = { 4, 5, 6 };
// Create a multimap with vectors as keys
multimap<VectorType, char> myMultimap;
myMultimap.insert(make_pair(vec1, 'a'));
myMultimap.insert(make_pair(vec2, 'b'));
// Print the multimap with vectors as keys
for (auto& pair : myMultimap) {
cout << "{ ";
for (auto& element : pair.first) {
cout << element << ", ";
}
cout << "}, " << pair.second << endl;
}
return 0;
}
Output
{ 1, 2, 3, }, a { 4, 5, 6, }, b
Time Complexity O(N), here N is the
number of elements in the multimap.
Auxiliary Space: O(N * M) where
M is the
size of the vectors.