Open In App

Group Vector of Pair Elements in Multimap

Multimap stores key-value pairs and for the same key, we can have more than one value i.e. multiple values for a single key. We can use this property of multimap to group vector of pair elements easily. In this article, we will discuss how to group elements of a vector of pairs in a multimap container.

Example



Input:
myVector ={ {"A", 80},{"B", 70},{"A", 90},{"C", 90},{"B", 60},{"A", 100}}

Output:
myMultiMap = { {"A", 80},{"A", 90},{"A", 100},{"B", 60},{"B", 70},{"C", 90}}

Grouping of Vector of Pair Elements

We can just create a multimap of the same type as a pair and insert the vector elements in the map using the insert function. After that, we can access all the key-value pairs with the same key using the std::multimap::equal_range() function.

C++ Program to Group Vector of Pairs Elements in a Multimap




// C++ Program to Demonstrate Multimap and Access All
// Key-Value Pairs
  
#include <iostream>
#include <map>
#include <vector>
  
using namespace std;
  
int main()
{
    // Create a multimap with pairs
    multimap<int, string> myMultiMap;
  
    // Insert vector elements into the multimap
    vector<pair<int, string> > elements
        = { { 1, "Apple" },
            { 2, "Banana" },
            { 1, "Apricot" },
            { 3, "Cherry" },
            { 2, "Blueberry" } };
  
    for (const auto& element : elements) {
        myMultiMap.insert(element);
    }
  
    // Access all key-value pairs for all keys
    cout << "All Key-Value pairs:" << endl;
    for (const auto& keyValuePair : myMultiMap) {
        int key = keyValuePair.first;
        auto range = myMultiMap.equal_range(key);
  
        cout << "Key: " << key << endl;
        for (auto it = range.first; it != range.second;
             ++it) {
            cout << "  Value: " << it->second << endl;
        }
    }
  
    return 0;
}

Output



All Key-Value pairs:
Key: 1
Value: Apple
Value: Apricot
Key: 1
Value: Apple
Value: Apricot
Key: 2
Value: Banana
Value: Blueberry
Key: 2
Value: Banana
Value: Blueberry
Key: 3
Value: Cherry

Time Complexity: O(N log(N))
Auxiliary Space: O(N)


Article Tags :