I am going back over older code that I had written before and I have noticed something that I dont actually understand. Code below. How is the sort and compare function working in this. It seems to be returning true when the inputs are a small number and then a large number, indicating that the smaller number is larger than the two. The program prints the numbers in reverse, so what I am assuming happens is not what actually is happening, but i cant seem to figure out how exactly it is working.
(Somebody else feel free to also reply in case I'm missing the question)
std::sort takes in a "compare" function (or function-like object) that it calls while doing the sorting. Normally, this compare function is expected to implement the logic of "a < b", which is used to sort things in ascending order. But if you instead implement "a > b", you'll get the opposite effect, and things will be sorted in descending order.
Here's a simple example that sorts just two items, by calling the compare function a single time (empty if statement just for clarity).
// Example program
#include <iostream>
#include <algorithm>
#include <functional>
template <typename T, typename Func>
void sort_two_items(T& first, T& second, Func compare)
{
if (compare(first, second))
{
// a < b
// assume items are already in order
}
else
{
// a > b
// swap them
std::swap(first, second);
}
}
int main()
{
int a = 42;
int b = 36;
std::cout << "a = " << a << ", b = " << b << "\n\n";
std::cout << "Sorting in ascending order...\n";
sort_two_items(a, b, std::less<>{});
std::cout << "a = " << a << ", b = " << b << '\n';
std::cout << "Sorting in descending order...\n";
sort_two_items(a, b, std::greater<>{});
std::cout << "a = " << a << ", b = " << b << '\n';
}
a = 42, b = 36
Sorting in ascending order...
a = 36, b = 42
Sorting in descending order...
a = 42, b = 36
The function you pass to sort should return true if its first argument is ordered-before its second argument. "Ordered before" isn't necessarily the same as "less than".