A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/cpp/initialize-multiset-with-custom-comparator-in-cpp/ below:

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

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

Last Updated : 23 Jul, 2025

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++
// 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;
}

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



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4