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 forward_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 forward_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
|
// 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;
}
|
输出
default sort (operator<): 5 13 22 31 40 62 90
sort with std::greater(): 90 62 40 31 22 13 5
|
复杂度
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.