Lambda Sort
Part of the Logic & Flow section of Coddy's C++ journey — lesson 47 of 56.
The C++ Standard Library provides a powerful function called std::sort from the <algorithm> header that can sort containers like vectors.
By default, std::sort arranges elements in ascending order (smallest to largest). However, you can customize this behavior by providing a lambda expression that defines how elements should be compared:
#include <vector>
#include <algorithm>
std::vector<int> numbers = {5, 2, 8, 1, 9};
// Sort in descending order using a lambda
std::sort(numbers.begin(), numbers.end(), [](int a, int b) {
return a > b; // Return true if a should come before b
});The lambda takes two parameters representing elements being compared and returns true if the first element should come before the second in the sorted result. For descending order, we return true when a > b, which places larger numbers first.
This demonstrates how lambdas make it easy to customize standard library functions without writing separate comparison functions, keeping your sorting logic right where you need it.
Challenge
EasyCreate a program that demonstrates custom sorting using lambda expressions with std::sort. This challenge will test your understanding of how to use lambda functions to define custom comparison logic for sorting containers.
The following inputs will be provided:
- An integer
nrepresenting the number of elements in the vector nintegers representing the elements to be sorted- A character
orderrepresenting the sorting order (Afor ascending,Dfor descending)
Your program should:
- Create a
std::vector<int>and populate it with the input numbers - Use
std::sortfrom the<algorithm>header with a lambda expression to sort the vector - The lambda should take two integer parameters and return a boolean value
- Based on the order character, implement the appropriate comparison logic in the lambda
- Print each element of the sorted vector on a separate line
The sorting behavior should be:
- If
orderisA: sort in ascending order (smallest to largest) - If
orderisD: sort in descending order (largest to smallest)
Use the following exact output format:
[first_sorted_element]
[second_sorted_element]
...
[last_sorted_element]Remember that std::sort takes three parameters: the beginning iterator, the ending iterator, and a comparison function. Use vector.begin() and vector.end() for the iterators. The lambda comparison function should return true if the first parameter should come before the second parameter in the sorted result. For ascending order, return a < b; for descending order, return a > b.
Cheat sheet
The std::sort function from the <algorithm> header sorts containers like vectors. By default, it sorts in ascending order, but you can customize the sorting behavior using a lambda expression.
Basic syntax:
std::sort(container.begin(), container.end(), comparison_lambda);The lambda takes two parameters representing elements being compared and returns true if the first element should come before the second in the sorted result.
Example - descending order:
#include <algorithm>
#include <vector>
std::vector<int> numbers = {5, 2, 8, 1, 9};
std::sort(numbers.begin(), numbers.end(), [](int a, int b) {
return a > b; // Larger numbers come first
});Example - ascending order:
std::sort(numbers.begin(), numbers.end(), [](int a, int b) {
return a < b; // Smaller numbers come first
});Try it yourself
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
// Read input
int n;
cin >> n;
vector<int> numbers(n);
for (int i = 0; i < n; i++) {
cin >> numbers[i];
}
char order;
cin >> order;
// TODO: Write your code below
// Use std::sort with a lambda expression to sort the vector
// based on the order character (A for ascending, D for descending)
// Output the sorted elements
for (int num : numbers) {
cout << num << endl;
}
return 0;
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Pointers and Memory
What is a Pointer?Address-Of OperatorDereference OperatorNull PointersPointers and ArraysDynamic Memory with 'new'Freeing Memory with 'delete'Recap - Pointer Practice2Vectors (Dynamic Arrays)
Introducing std::vectorCreating a VectorAdding ElementsAccessing ElementsVector SizeIterating with a For LoopRange-Based For LoopRemoving ElementsRecap - Vector Operations5Project: Inventory Tool
Project SetupAdding and Updating Items