0

How to sort classes

How can we sort class values with heap sort

22nd Nov 2018, 6:21 AM
batuhan özdöl
batuhan özdöl - avatar
1 Odpowiedź
+ 1
I hope I interpreted your question correctly as "How to sort objects of a class inside a heap?", because otherwise this won't be a help: If we consider std::heap_sort() as an example, you can see that the function uses the '<' operator in order to compare the values to sort. You can view it here: http://www.cplusplus.com/reference/algorithm/sort_heap/ Now you have two possibilities: You can overload the '<' operator for your class and use that operator for the sort, or you create a function that takes in two objects of your class and returns which one should be considered 'smaller' or 'bigger', expressed as a boolean value, and give that function as an argument to your sorting function. The point is, you have to provide a way for the compiler to decide how to compare your objects.
22nd Nov 2018, 9:01 PM
Shadow
Shadow - avatar