Using a Custom Comparison Function for Sorting a Vector

C++ provides the std::sort function from the algorithm library to sort a vector. By default, it sorts elements in ascending order using the < operator. However, you can use a custom comparison function to define your own sorting logic. This is useful when you want the sorting happen in descending order, or based on complex criteria.

Syntax

The syntax to import the required libraries and use the std::sort function with the custom comparison function is as shown in the following.

</>
Copy
#include <algorithm>
#include <vector>

// Custom comparison function
bool customComparison(T a, T b) {
    // Your comparison logic here
    return condition;
}

// Sort with a custom comparison function
std::sort(vector.begin(), vector.end(), customComparison);

Examples

Example 1: Sorting in Descending Order

This example demonstrates how to use a custom comparison function to sort a vector in descending order.

</>
Copy
#include <iostream>
#include <algorithm>
#include <vector>

// Custom comparison function for descending order
bool descending(int a, int b) {
    return a > b;
}

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

    // Sort the vector in descending order
    std::sort(numbers.begin(), numbers.end(), descending);

    std::cout << "Sorted in descending order: ";
    for (const auto& num : numbers)
        std::cout << num << " ";
    std::cout << std::endl;

    return 0;
}

Output:

Sorted in descending order: 8 5 4 3 1

Example 2: Sorting Based on Even-First Rule

This example sorts a vector of integers such that even numbers appear before odd numbers, and numbers within each group are sorted in ascending order.

</>
Copy
#include <iostream>
#include <algorithm>
#include <vector>

// Custom comparison function: even numbers first
bool evenFirst(int a, int b) {
    if ((a % 2 == 0) && (b % 2 != 0)) return true; // Even comes before odd
    if ((a % 2 != 0) && (b % 2 == 0)) return false; // Odd comes after even
    return a < b; // Sort within groups in ascending order
}

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

    // Sort the vector using the custom comparison function
    std::sort(numbers.begin(), numbers.end(), evenFirst);

    std::cout << "Sorted with even-first rule: ";
    for (const auto& num : numbers)
        std::cout << num << " ";
    std::cout << std::endl;

    return 0;
}

Output:

Sorted with even-first rule: 4 6 8 1 3 5

Even numbers in ascending order comes first, followed by the odd numbers in ascending order.