How Can I Get All the Unique Keys in a Multimap?
Last Updated :
29 Jan, 2024
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++
#include <iostream>
#include <map>
#include <set>
using namespace std;
int main()
{
multimap< int , char > mymm
= { { 1, 'a' }, { 2, 'p' }, { 3, 'e' },
{ 2, 'r' }, { 4, 'c' }, { 3, 'x' } };
set< int > uniqueKeys;
for ( auto & it : mymm) {
uniqueKeys.insert(it.first);
}
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.
Share your thoughts in the comments
Please Login to comment...