To sort a list in ascending order in C++ using std::list, you can use the sort()
method provided by the list class.
In this example,
and
.numbers
with integer values.sort()
method on the numbers
list to sort it in ascending order.sort()
method sorts the elements in place, modifying the original list.#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 (const int& num : numbers) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
Sorted list in ascending order: 1 2 3 5 8
In this example,
and
.words
with string values.sort()
method on the words
list to sort it in ascending order.sort()
method sorts the elements in place, modifying the original list.#include <iostream>
#include <list>
#include <string>
int main() {
std::list<std::string> words = {"banana", "apple", "cherry"};
words.sort();
std::cout << "Sorted list in ascending order: ";
for (const std::string& word : words) {
std::cout << word << " ";
}
std::cout << std::endl;
return 0;
}
Sorted list in ascending order: apple banana cherry
In this tutorial, we learned How to Sort a List in Ascending Order in C++ language with well detailed examples.