How to Sort User-Defined Types Using std::sort?
Last Updated :
25 Jan, 2024
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++
#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) {}
bool operator<( const Complex& obj)
{
if ( this ->real == obj.real) {
return this ->imag < obj.imag;
}
return this ->real < obj.real;
}
};
int main()
{
std::vector<Complex> vec = {
{ 1, 2 }, { 3, 1 }, { 2, 2 }, { 1, 3 }, { 2, 1 }
};
std::sort(vec.begin(), vec.end());
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()
{
vector<Complex> vec = {
{ 1, 2 }, { 3, 1 }, { 2, 2 }, { 1, 3 }, { 2, 1 }
};
sort(vec.begin(), vec.end(),
[]( const Complex& a, const Complex& b) {
if (a.real == b.real) {
return a.imag < b.imag;
}
return a.real < b.real;
});
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.
Share your thoughts in the comments
Please Login to comment...