Open In App

Custom Comparator in C++

Last Updated : 21 Aug, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

A custom comparator in C++ is a way to tell a container (like set or sort) how to compare and order elements differently than the default. Instead of using the usual "less than" (<), we can define our own rule.

For example, you can make it sort in descending order or by a specific property of a complex object. It's like giving the container our own sorting instructions.

How to Create a Comparator in C++?

In C++, we can create a comparator function using four methods. They are:

  1. Using Function Pointer
  2. Using Lambda Expression
  3. Using Functors

1. Comparator Using Function Pointer

In this method, we define a function that implements the comparison logic and returns some value. Then we use the pointer to this function as the comparator.

Example

C++
// C++ program to create comparator using function pointer
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

// Custom comparison function
bool customComparison(int a, int b)
{
    // Custom comparison logic
    return a < b; // it sorts in ascending order
}

int main()
{
    // Creating a vector of integers
    vector<int> myVec = { 7, 5, 2, 1, 4, 3 };

    // Using sort with a function pointer
    sort(myVec.begin(), myVec.end(), customComparison);

    // Displaying the sorted vector
    cout << "Sorted Vector: ";
    for (int num : myVec) {
        cout << num << " ";
    }
    cout << endl;

    return 0;
}

Output
Sorted Vector: 1 2 3 4 5 7 

2. Comparator Using Lambda Expression

Lambda expressions can be used to declare the inline function definitions. We can also use the lambda expression to create a comparator just like we can do with function. Moreover, we can declare the lambda expression in a place where the comparator is required.

Example

C++
// C++ program to create comparator using Lambda function
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

int main()
{
    // Creating a vector of integers
    vector<int> myVec = { 4, 3, 8, 1, 7, 2 };

    // Using sort() with a lambda function
    sort(myVec.begin(), myVec.end(), [](int a, int b) {
        // Custom comparison logic
        return a < b; // this sorts in ascending order
    });

    // printing sorted vector
    cout << "Sorted Vector: ";
    for (int i : myVec) {
        cout << i << " ";
    }
    cout << endl;
    return 0;
}

Output
Sorted Vector: 1 2 3 4 7 8 

3. Comparator Using Functor (Function Object)

A functor (Function Object) is a class or struct that overloads the operator() such that it behaves as a function when called. We can also use such objects as a comparator by defining the comparison logic inside the () operator overloading function.

Example

C++
// C++ program to create comparator using functor

#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

// defining Functor (Function Object)
struct Comparator {
    bool operator()(int a, int b) const
    {
        // Custom comparison logic
        return a < b; // this sorts in ascending order
    }
};

int main()
{
    // Creating a vector of integers
    vector<int> myVec = { 9, 2, 4, 1, 6, 3 };

    // Using sort() with a functor (function object)
    sort(myVec.begin(), myVec.end(), Comparator());

    // Printing the sorted vector
    cout << "Sorted Vector: ";
    for (int i : myVec) {
        cout << i << " ";
    }
    cout << endl;

    return 0;
}

Output
Sorted Vector: 1 2 3 4 6 9 

Application of Comparator in C++

In C++, comparator is widely used in many different cases. Some of the common application of comparators is as follows:

1. Sort the Characters in increasing frequency.

It can be used to count and sort characters in the string based on increasing frequency using a custom comparator.

Example

The below example demonstrates the use of comparator to sort the characters in increasing frequency.

C++
 // C++ program to demonstrate the use of comparator to sort the characters in increasing frequency.

#include <iostream>
#include <map> 
#include <algorithm>
using namespace std;

int main() {
    string s = "Heellloooo";

    // Creating a map to store the frequency of each character
    map<char, int> mp;
    
    // Counting the frequency of each character in the string
    for (int i = 0; i < s.length(); i++) {
        mp[s[i]]++;
    }

    // Lambda function 'compare' to serve as a custom comparator for sorting
    auto compare = [&](char a, char b) { return mp[a] > mp[b]; };

    // Sort the string based on character frequency using the custom comparator
    sort(s.begin(), s.end(), compare);

    // Display the sorted string based on character frequency
    cout << s;

    return 0;
}

Output
oooollleeH

2. Sort characters in increasing frequency and same frequency in decreasing alphabetical order.

It can be used to count and sort characters in the string based on increasing frequency and same frequency using a custom comparator.

Example

C++
// C++ program to demonstrate the use of comparator to sort
// the characters in increasing frequency and same frequency
// in decreasing alphabetical order.

#include <iostream>
using namespace std;
#include <algorithm>
#include <map>

int main()
{
    // Input string
    string s = "hellloooo geek";

    // Creating a map to store the frequency of each
    // character
    map<char, int> mp;

    // Counting the frequency of each character in the
    // string
    for (int i = 0; i < s.length(); i++) {
        mp[s[i]]++;
    }

    // here  Lambda function 'compare' to serve as a custom
    // comparator for sorting
    auto compare = [&](char a, char b) {
        if (mp[a] == mp[b]) {
            return a > b;
        }
        return mp[a] > mp[b];
    };

    // Sort the string based on character frequency using
    // the custom comparator
    sort(s.begin(), s.end(), compare);

    // print sorted string based on character frequency
    cout << s;

    return 0;
}

Output
oooollleeekhg 

3. Sort numbers by increasing set bit count

It is used to sort a vector of integers based on the number of set bits using a lambda function as the custom comparator.

Example

C++
#include <iostream>
using namespace std;
#include <bits/stdc++.h>

int main()
{
    // Initializing a vector of integers
    vector<int> p = { 1, 5, 8, 13, 2, 17 };

    // Lambda function 'lamda' to compare integers based on
    // the number of set bits (population count)
    auto lamda = [&](int a, int b) {
        return __builtin_popcount(a)
               < __builtin_popcount(b);
    };

    // Sort the vector 'p' based on the number of set bits
    // using the custom lambda comparator
    sort(p.begin(), p.end(), lamda);

    // print the sorted vector
    for (auto it : p) {
        cout << it << " ";
    }

    return 0;
}

Output
1 8 2 5 17 13 

4. Segregate even odd numbers and even numbers first.

We can used comparator to sort a vector of integers to segregate even and odd numbers, placing even numbers before odd numbers.

Example

C++
// C++ program to Segregate even odd numbers and even
// numbers before odd numbers.

#include <iostream>
using namespace std;
#include <algorithm>
#include <vector>

int main()
{
    // Initialize a vector of integers
    vector<int> p = { 1, 2, 3, 4, 5, 6, 7 };

    // Lambda function 'compare' to segregate even and odd
    // numbers, placing even numbers before odd numbers
    auto compare
        = [&](int a, int b) { return a % 2 < b % 2; };

    // Sort the vector 'p' based on the segregation criteria
    // using the custom lambda comparator
    sort(p.begin(), p.end(), compare);

    // printing vector after segregation
    cout << "after segregation: ";
    for (auto it : p) {
        cout << it << " ";
    }

    return 0;
}

Output
after segregation: 2 4 6 1 3 5 7 

Advantages of custom comparators

  • Custom Sorting logic: We can define our own way to sort elements (e.g., descending, by name, by age).
  • Works with Complex data
  • Flexible with STL containers
  • Improves Code Reusability

Article Tags :