![]() |
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 TypesFor 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::sortC++
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 ComparatorC++
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. |
Reffered: https://www.geeksforgeeks.org
C++ |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 10 |