public member function
<forward_list>

std::forward_list::sort

(1)
  void sort();
(2)
template <class Compare>
  void sort (Compare comp);
Sort elements in container
Sorts the elements in the forward_list, altering their position within the container.

The sorting is performed by applying an algorithm that uses either operator< (in version (1)) or comp (in version (2)) to compare elements. This comparison shall produce a strict weak ordering of the elements (i.e., a consistent transitive comparison, without considering its reflexiveness).

The resulting order of equivalent elements is stable: i.e., equivalent elements preserve the relative order they had before the call.

The entire operation does not involve the construction, destruction or copy of any element object. Elements are moved within the container.

Parameters

comp
Binary predicate that, taking two values of the same type of those contained in the forward_list, returns true if the first argument goes before the second argument in the strict weak ordering it defines, and false otherwise.
This shall be a function pointer or a function object.

Return value

none

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 << '\n';

  mylist.sort(std::greater<int>());

  std::cout << "sort with std::greater():";
  for (int& x: mylist) std::cout << ' ' << x;
  std::cout << '\n';

  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

No changes.

Data races

The container is modified.
All contained elements are accessed (but not modified). Concurrently iterating through the container is not safe.

Exception safety

Basic guarantee: if an exception is thrown, the container is in a valid state.
It throws if the comparison or the moving operation of any element throws.

See also