To sort a list in descending order in C++ using std::list, you can use the list's member function sort
with a custom comparison function.
In this example,
numbers
using std::list with integer values.compare
that compares elements in reverse order (descending).sort
with compare
as the argument to sort the list in descending order.#include <iostream>
#include <list>
// Custom comparison function for descending order
bool compare(int a, int b) {
return a > b;
}
int main() {
std::list<int> numbers = {5, 2, 8, 1, 3};
numbers.sort(compare);
// Print sorted list
for (int num : numbers) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
8 5 3 2 1
In this example,
words
using std::list with string values.compare
that compares strings in reverse order (descending).sort
with compare
as the argument to sort the list of strings in descending order.#include <iostream>
#include <list>
#include <algorithm>
// Custom comparison function for descending order
bool compare(const std::string& a, const std::string& b) {
return a > b;
}
int main() {
std::list<std::string> words = {"banana", "apple", "cherry"};
words.sort(compare);
// Print sorted list
for (const std::string& word : words) {
std::cout << word << " ";
}
std::cout << std::endl;
return 0;
}
cherry banana apple
In this tutorial, we learned How to Sort a List in Descending Order in C++ language with well detailed examples.