A RetroSearch Logo

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

Search Query:

Showing content from https://www.geeksforgeeks.org/cpp/how-to-use-custom-comparator-with-set-in-cpp/ below:

How to Use Custom Comparator with Set in C++?

How to Use Custom Comparator with Set in C++?

Last Updated : 23 Jul, 2025

In C++, sets are associative containers that store unique elements in some sorted order. By default, set store data in increasing order but we can change this using a custom comparator. In this article, we will learn, how to declare a set with a custom comparator in C++ STL.

Example

Input:
Data =  {1, 5, 3, 4, 2}

Output:
mySet = {5, 4, 3, 2, 1}
Declare a Set with a Custom Comparator in C++

To declare a set with a custom comparator in C++, we have to pass the comparator function to the set at the time of its declaration. This function will then be used to determine the order of elements in the set.

Syntax
std::set<T, Compare_Type> mySet;

Here, T is the type of elements in the set, and Compare is the type of the comparator.

C++ Program to Declare a Set with a Custom Comparator C++
// C++ Program to illustrate how to declare a set with a
// custom comparator
#include <cmath>
#include <iostream>
#include <set>
using namespace std;
// Custom comparator for sorting integers based on absolute
// values
struct AbsoluteValueComparator {
    bool operator()(int a, int b) const
    {
        return abs(a) < abs(b);
    }
};

int main()
{
    // Declare a set of integers with the custom comparator
    set<int, AbsoluteValueComparator> mySet;

    // Insert elements into the set
    mySet.insert(-5);
    mySet.insert(3);
    mySet.insert(-8);
    mySet.insert(2);

    // Print the elements in the set (sorted based on
    // absolute values)
    cout << "Elements in the set: ";
    for (int element : mySet) {
        cout << element << " ";
    }

    return 0;
}

Output
Elements in the set: 2 3 -5 -8 


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