To sort a std::list in C++, you can use the sort()
method. For sorting in ascending order, you simply call the sort()
method on the list object. For sorting in descending order, you can use the sort()
method with a comparison function.
In this example,
and
.std::list
named numbers
and initialize it with integer values.sort()
method on the numbers
list to sort it in ascending order.sort()
method sorts the elements in natural order.#include <iostream>
#include <list>
int main() {
std::list<int> numbers = {5, 2, 8, 1, 3};
numbers.sort();
std::cout << "Sorted list in ascending order: ";
for (int n : numbers) {
std::cout << n << " ";
}
std::cout << std::endl;
return 0;
}
Sorted list in ascending order: 1 2 3 5 8
In this example,
and
.std::list
named numbers
and initialize it with integer values.sort()
method on the numbers
list with a comparison function to sort it in descending order.sort()
method with the comparison function sorts the elements in reverse natural order.#include <iostream>
#include <list>
bool compare(int a, int b) {
return a > b;
}
int main() {
std::list<int> numbers = {5, 2, 8, 1, 3};
numbers.sort(compare);
std::cout << "Sorted list in descending order: ";
for (int n : numbers) {
std::cout << n << " ";
}
std::cout << std::endl;
return 0;
}
Sorted list in descending order: 8 5 3 2 1
In this tutorial, we learned How to Sort a List in C++ language with well detailed examples.