public member function
<forward_list>
(1) | void sort ( );
|
---|
(2) | template <class Compare>
void sort ( Compare comp ); |
---|
Sort elements in container
Sorts the elements in the container from lower to higher. The sorting is performed by comparing the elements in the container in pairs using a sorting algorithm.
In the version taking no parameters (1), the comparisons are performed using the operator< between the elements being compared.
In the second version (2), the comparisons are perfomed using comp, which is used to perform weak strict ordering. This requires the comparison to be be transitive but not reflexive.
The entire operation does not involve the construction, destruction or copy of any element object. Elements are moved within the container.
Parameters
- comp
- Comparison function that, taking two values of the same type of those contained in the list object, returns true if the first argument goes before the second argument in the specific order (i.e., if the first is less than the second), and false otherwise.
Compare can either be a function pointer type or a class that overloads operator().
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
// forward_list::sort
#include <iostream>
#include <forward_list>
#include <functional>
int main ()
{
std::forward_list<int> mylist = {22, 13, 5, 40, 90, 62, 31};
mylist.sort();
std::cout << "default sort (operator<):";
for (int& x: mylist) std::cout << " " << x;
std::cout << std::endl;
mylist.sort(std::greater<int>());
std::cout << "sort with std::greater():";
for (int& x: mylist) std::cout << " " << x;
std::cout << std::endl;
return 0;
}
|
Output:
default sort (operator<): 5 13 22 31 40 62 90
sort with std::greater(): 90 62 40 31 22 13 5
|
Complexity
Approximately NlogN where N is the container size.
Iterator validity
All the iterators, pointers and references remain valid after the sort and refer to the same elements they were referring to before.