Custom Comparator for Multimap in C++
Last Updated :
05 Mar, 2024
In C++ multimap is a container to store key-value pairs allowing duplicate keys which is not allowed in a map container. By default, the multimap container uses the less than ‘<‘ operator to compare the keys for ordering the entries but also allows the use of the custom comparator. In this article, we will learn how to use a multimap with a custom comparator in C++.
Custom Comparator for Multimap in C++
To use a std::multimap with a custom comparator, we can define a comparison function or a functor (a class that overloads the operator()
) and then use it as a template parameter when declaring the multimap so that the elements of the multimap will be ordered automatically based on the conditions mentioned in the custom comparator.
C++ Program to Use a Multimap with a Custom Comparator
The below example demonstrates how we can use a multimap with a custom comparator in C++.
C++
#include <iostream>
#include <map>
#include <string>
using namespace std;
struct CustomComparator {
bool operator()( const string& a, const string& b) const
{
return a.length() < b.length();
}
};
int main()
{
multimap<string, int , CustomComparator> mp2
= { { "apple" , 5 },
{ "apple" , 10 },
{ "banana" , 3 },
{ "orange" , 4 },
{ "kiwi" , 2 } };
cout << "Multimap using custom comparator" << endl;
for ( auto pair : mp2) {
cout << pair.first << ": " << pair.second << endl;
}
return 0;
}
|
Output
Multimap using custom comparator
kiwi: 2
apple: 5
apple: 10
banana: 3
orange: 4
Time Complexity: O(N log N), here N is the number of elements in a multimap.
Auxiliary Space: O(N)
Share your thoughts in the comments
Please Login to comment...