How to Initialize Multiset with Custom Comparator in C++?
Last Updated :
07 Feb, 2024
In C++, a multiset container stores the data in a sorted order. By default, this order is increasing order (using < operator as comparator) but we can change this order by providing a custom comparator. In this article, we will learn how to initialize a multiset with a custom comparator function in C++.
For Example,
Input: 1 8 6 4 9 3 2 5 7
Output: myMultiset = {9, 8, 7, 6, 5, 4, 3, 2, 1}
Initialize a Multiset with a Custom Comparator in C++
The comparator is a binary predicate function that compares the two values and returns true if the order needs to be changed and false if the order is already correct. We can declare this comparator as a function, functor, or lambda expression and pass it as an argument to the std::multiset constructor.
C++ Program to Initialize a Multiset with a Custom Comparator in C++
C++
#include <iostream>
#include <set>
using namespace std;
int main()
{
auto customComparator
= []( const int & a, const int & b) { return a > b; };
multiset< int , decltype (customComparator)> customSet(
customComparator);
customSet.insert(5);
customSet.insert(2);
customSet.insert(8);
for ( const auto & element : customSet) {
cout << element << " " ;
}
return 0;
}
|
Time Complexity: O(N logN), where N is the number of elements to be inserted.
Space Complexity: O(N)
Share your thoughts in the comments
Please Login to comment...