Open In App

How Can I Get All the Unique Keys in a Multimap?

In C++, multimap stores key-value pairs like map but they allow users to store duplicate keys. It means that the same key can occur multiple times. In this article, we will learn how to extract the unique key from a multimap

Example



Input: myMmap = { {1, 'a' },  {2, 'p'},  {3, 'e'},  {2, 'r'}, {4, 'c'}, {3, 'x'} }

Output: {1, 2, 3, 4}

Extract Unique Keys from a Multimap in C++

We can create a set container and insert all the keys of the multimap in that set. The set container only stores the unique values so the duplicate keys will already be rejected.

C++ Program to Extract the Keys from a Multimap




// C++ program to demonstrate the use of a set to extract
// unique keys in a multimap.
#include <iostream>
#include <map>
#include <set>
using namespace std;
  
int main()
{
    // Create and populate a multimap with some values
    multimap<int, char> mymm
        = { { 1, 'a' }, { 2, 'p' }, { 3, 'e' },
            { 2, 'r' }, { 4, 'c' }, { 3, 'x' } };
  
    // Create a set to store unique keys
    set<int> uniqueKeys;
  
    for (auto& it : mymm) {
        // Collect unique keys in the set
        uniqueKeys.insert(it.first);
    }
  
    // Print unique keys
    cout << "Unique Keys:" << endl;
    for (const auto& key : uniqueKeys) {
        cout << key << " ";
    }
  
    return 0;
}

Output

Unique Keys:
1 2 3 4 

Explanation: In the above example we use a std::set named uniqueKeys to store the unique keys from the multimap. The for loop iterates through the multimap, and the upper_bound function is used to jump to the next different key in the multimap. Inside the loop, we insert each unique key into the set.

We can also use unordered_set here in order to do the insertion faster but in this process we lose the order of the keys.

Article Tags :