public member function
<list>

std::list::sort

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

The sorting is performed by applying an algorithm that uses eitheroperator<(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.

参数

comp
Binary predicate that, taking two values of the same type of those contained in the list, returnstrueif the first argument goes before the second argument in the strict weak ordering it defines, andfalse否则为 false。
This shall be a function pointer or a function object.

返回值



示例

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
// list::sort
#include <iostream>
#include <list>
#include <string>
#include <cctype>

// comparison, not case sensitive.
bool compare_nocase (const std::string& first, const std::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;
  }
  return ( first.length() < second.length() );
}

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

  mylist.sort();

  std::cout << "mylist contains:";
  for (it=mylist.begin(); it!=mylist.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';

  mylist.sort(compare_nocase);

  std::cout << "mylist contains:";
  for (it=mylist.begin(); it!=mylist.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';

  return 0;
}

输出
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 functioncompare_nocasethe comparison is made case insensitive.

复杂度

ApproximatelyNlogN,其中Nis the container size.

迭代器有效性

没有变化。

数据竞争

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

异常安全

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.

另见