![]() |
VOOZH | about |
In C++ STL, maps are used to store key-value pairs but they only allow one value for a key. Sometimes, we might want multiple values to be associated with a single key. In this article, we will learn how to store multiple values for the same key in C++.
Example:
Input:
Key:1; Value:Red
Key:1; Value:Blue
Key:1; Value:Green
Key:2; Value:Apple
Key:2; Value:Mango
Key:2; Value:Banana
Output:
Key: 1, Values: Red Blue Green
Key: 2, Values: Apple Mango Banana
In C++, if we want to associate multiple values with the same key, we can use std::multimap that allows us to store multiple elements that have the same key and also permits the storage of duplicate keys for the same value. To insert elements into the multimap, use the std::multimap::insert()function.
The below program demonstrates how we can use multiple values for the same key in C++.
Multimap: Key: 1, Values: Red Blue Green Key: 2, Values: Apple Mango Banana
Time Complexity: O(log n), here n is the number of elements in the multimap.
Auxilliary Space : O(n)