How to Sort in Descending Order in C++: Simple Guide
To sort in descending order in C++, use
std::sort with a custom comparator like std::greater<>() or a lambda function. For example, std::sort(vec.begin(), vec.end(), std::greater<>()); sorts a vector from largest to smallest.Syntax
The std::sort function sorts elements in a range. To sort in descending order, provide a comparator that defines the order.
std::sort(start, end, comparator);sorts elements fromstarttoendusingcomparator.std::greater<>()is a built-in comparator that sorts in descending order.- You can also use a lambda function like
[](int a, int b) { return a > b; }for custom sorting.
cpp
std::sort(container.begin(), container.end(), std::greater<>());
Example
This example shows how to sort a vector of integers in descending order using std::greater<>(). It prints the vector before and after sorting.
cpp
#include <iostream> #include <vector> #include <algorithm> #include <functional> // for std::greater int main() { std::vector<int> numbers = {5, 2, 9, 1, 5, 6}; std::cout << "Before sorting: "; for (int n : numbers) { std::cout << n << ' '; } std::cout << '\n'; std::sort(numbers.begin(), numbers.end(), std::greater<>()); std::cout << "After sorting (descending): "; for (int n : numbers) { std::cout << n << ' '; } std::cout << '\n'; return 0; }
Output
Before sorting: 5 2 9 1 5 6
After sorting (descending): 9 6 5 5 2 1
Common Pitfalls
Common mistakes when sorting in descending order include:
- Forgetting to include the comparator, which results in ascending order.
- Using
std::less<>()or no comparator, which sorts ascending by default. - Passing incorrect iterators or container types.
Always ensure the comparator matches the desired order.
cpp
#include <algorithm> #include <vector> // Wrong: sorts ascending (default) // std::sort(vec.begin(), vec.end()); // Right: sorts descending // std::sort(vec.begin(), vec.end(), std::greater<>());
Quick Reference
| Usage | Description |
|---|---|
| std::sort(begin, end); | Sorts in ascending order by default |
| std::sort(begin, end, std::greater<>()); | Sorts in descending order using built-in comparator |
| std::sort(begin, end, [](auto a, auto b) { return a > b; }); | Sorts in descending order using lambda function |
Key Takeaways
Use std::sort with std::greater<>() to sort in descending order easily.
Without a comparator, std::sort sorts in ascending order by default.
You can use a lambda function for custom descending order sorting.
Always pass valid iterators to std::sort to avoid runtime errors.
Include and headers when using std::sort and std::greater.