Open In App

How to Sort User-Defined Types Using std::sort?

Last Updated : 25 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

C++ provides a powerful sorting algorithm through the std::sort function. While this algorithm seamlessly works with standard data types, sorting user-defined types still requires additional steps. In this article, we discuss how to sort user-defined types using ‘std::sort’.

std::sort for User-Defined Data Types

For std::sort to work with user-defined data types such as class, and structs, we can simply define the behaviors of comparison operator for it using operator overloading. By default, the std::sort function uses < (less than the operator) for value comparison. We can overload this operator in our class for std::sort to work.

C++ Program to Sort User-Defined Data Types Using std::sort

C++




// C++ program to illustrate how to use std::sort function
// with user defined custom data types
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
  
class Complex {
public:
    double real;
    double imag;
  
    Complex(double r = 0, double i = 0): real(r), imag(i) {}
  
    // Define a custom comparison operator for sorting
    // Complex objects
    bool operator<(const Complex& obj)
    {
        // First, compare the real parts of the Complex
        // numbers
        if (this->real == obj.real) {
            // If the real parts are equal, compare the
            // imaginary parts
            return this->imag < obj.imag;
        }
        // If the real parts are different, use them for
        // comparison
        return this->real < obj.real;
    }
};
  
// driver code
int main()
{
    // Create a vector of Complex numbers
    std::vector<Complex> vec = {
        { 1, 2 }, { 3, 1 }, { 2, 2 }, { 1, 3 }, { 2, 1 }
    };
  
    // Sort the vector of Complex numbers using the custom
    // comparison operator
    std::sort(vec.begin(), vec.end());
  
    // Print the sorted Complex numbers
    for (auto i : vec) {
        cout << "( " << i.real << ", i" << i.imag << " )\n";
    }
  
    return 0;
}


Output

( 1, i2 )
( 1, i3 )
( 2, i1 )
( 2, i2 )
( 3, i1 )

In the above program, the std::sort function can work because we have defined the behavior of its default comparison operator < for our complex class. But again, if we need to sort in any different order, we will have to use the comparator with the std::sort function.

C++ Program to Sort User-Defined Data Types Using std::sort Using Comparator

C++




#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
  
class Complex {
public:
    double real;
    double imag;
  
    Complex(double r = 0, double i = 0): real(r)
        , imag(i){}
};
  
int main()
{
    // Create a vector of Complex numbers
    vector<Complex> vec = {
        { 1, 2 }, { 3, 1 }, { 2, 2 }, { 1, 3 }, { 2, 1 }
    };
  
    // Sort the vector using a custom comparator function
    sort(vec.begin(), vec.end(),
         [](const Complex& a, const Complex& b) {
             // Compare Complex numbers based on their real
             // parts
             if (a.real == b.real) {
                 // If real parts are equal, compare based
                 // on imaginary parts
                 return a.imag < b.imag;
             }
             // If real parts are different, use them for
             // comparison
             return a.real < b.real;
         });
  
    // Print the sorted vector
    cout << "( real, imaginary)" << endl;
    for (const auto& num : vec) {
        cout << "( " << num.real << ", " << num.imag
             << " )\n";
    }
  
    return 0;
}


Output

( real, imaginary)
( 1, 2 )
( 1, 3 )
( 2, 1 )
( 2, 2 )
( 3, 1 )

In this above program, we have used a comparator instead of the overloading operator. This method is more flexible as we can have any type of order in the sorting using a comparator. The same is not possible for the operator overloading method. The disadvantage is that we have to define a comparator and pass it to sort.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads