### stl sort function

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.

 ``1234567891011121314151617181920212223242526272829303132`` `````` #include #include #include int main() { std::vectornums = { 1, 2, 3, 4, 5 }; auto funct = []() { std::cout << "Lambda function\n"; }; funct(); auto compare = [](int const &a, int const &b) { return a > b; }; sort(nums.begin(), nums.end(), compare); for (auto i = nums.begin(); i < nums.end(); i++) { std::cout << *i << '\n'; } } ``````
(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).
 ``123456789101112131415161718192021222324252627282930313233343536`` ``````// Example program #include #include #include template 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```
Last edited on
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".
Last edited on
Topic archived. No new replies allowed.