C++ list sort() Function
Example
Sort a list alphabetically:
list<string> cars = {"Volvo", "BMW", "Ford", "Mazda"};
cars.sort();
for (string car : cars) {
cout << car << "\n";
}
Definition and Usage
The sort() function sorts the elements of a list in ascending order. Strings are sorted alphabetically, and numbers from the lowest to the highest.
You cannot use the sort() function from the <algorithm> library on a list, because it needs to jump directly to any position. Use the list's own sort() function instead.
The sort function is defined in the <list> header file.
Tip: To sort in descending order, use cars.sort(greater<string>());. greater is found in the <functional> library.
Syntax
list.sort();
list.sort(compare);
Parameter Values
| Parameter | Description |
|---|---|
| compare | Optional. A function that decides the order. It takes two elements, and returns true if the first element should come before the second. |
Technical Details
| Returns: | Nothing (void). |
|---|
Related Pages
Read more about lists in our List Tutorial.