public member function

std::list::sort

<list>
  void sort ( );
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 first version, taking no parameters, the comparisons are performed using the operator< between the elements being compared.

In the second version, 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. They 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.

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
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// list::sort
#include <iostream>
#include <list>
#include <string>
#include <cctype>
using namespace std;

// comparison, not case sensitive.
bool compare_nocase (string first, string second)
{
  unsigned int i=0;
  while ( (i<first.length()) && (i<second.length()) )
  {
    if (tolower(first[i])<tolower(second[i])) return true;
    else if (tolower(first[i])>tolower(second[i])) return false;
    ++i;
  }
  if (first.length()<second.length()) return true;
  else return false;
}

int main ()
{
  list<string> mylist;
  list<string>::iterator it;
  mylist.push_back ("one");
  mylist.push_back ("two");
  mylist.push_back ("Three");

  mylist.sort();

  cout << "mylist contains:";
  for (it=mylist.begin(); it!=mylist.end(); ++it)
    cout << " " << *it;
  cout << endl;

  mylist.sort(compare_nocase);

  cout << "mylist contains:";
  for (it=mylist.begin(); it!=mylist.end(); ++it)
    cout << " " << *it;
  cout << endl;

  return 0;
}


Output:
mylist contains: Three one two
mylist contains: one Three two
For default strings, the comparison is a strict character code comparison, where all uppercase letters compare lower than all lowercase letters, putting all strings beginning by an uppercase letter before in the first sorting operation.

Using the function compare_nocase the comparison is made case insensitive.

Complexity

Approximately NlogN where N is the list size.

See also