Comparator

A comparator is a function or an object used to define the ordering or comparison between two elements. It is often used in sorting algorithms or data structures like sets and maps. Here’s an example of how to use a comparator in C++:

#include <iostream>
#include <vector>
#include <algorithm>

// Custom comparator function
bool compare(int a, int b) {
    return a > b;  // Sort in descending order
}

int main() {
    std::vector<int> numbers = {5, 2, 8, 1, 9, 3};

    // Sorting the vector using the custom comparator
    std::sort(numbers.begin(), numbers.end(), compare);

    // Displaying the sorted vector
    for (int num : numbers) {
        std::cout << num << " ";
    }
    std::cout << std::endl;

    return 0;
}

In this example, we have a custom comparator function called compare that takes two integers a and b as parameters. The function compares the values of a and b and returns true if a should be placed before b in the sorted order. In this case, the function sorts the vector in descending order.

We use the std::sort algorithm to sort the vector numbers using the custom comparator function compare. Finally, we iterate over the sorted vector and print the elements to the console.

The output of this program will be:

9 8 5 3 2 1

As you can see, the elements are sorted in descending order based on the custom comparator function.

Leave a Reply

Your email address will not be published. Required fields are marked *