Open In App

How to Initialize Multiset with Custom Comparator in C++?

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++ Program to demonstrate the initialization of custom
// comparator with a multiset
#include <iostream>
#include <set>
  
using namespace std;
  
int main()
{
    // Define a custom comparator lambda function
    auto customComparator
        = [](const int& a, const int& b) { return a > b; };
  
    // Create a multiset with the custom comparator
    multiset<int, decltype(customComparator)> customSet(
        customComparator);
  
    // Insert elements into the multiset
    customSet.insert(5);
    customSet.insert(2);
    customSet.insert(8);
  
    // Print elements of the multiset
    for (const auto& element : customSet) {
        cout << element << " ";
    }
  
    return 0;
}

Output

8 5 2 

Time Complexity: O(N logN), where N is the number of elements to be inserted.
Space Complexity: O(N)


Article Tags :