std::forward_list<T,Allocator>:: sort
|
void
sort
(
)
;
|
(1) |
(自 C++11 起)
(自 C++26 起为 constexpr) |
|
template
<
class
Compare
>
void sort ( Compare comp ) ; |
(2) |
(自 C++11 起)
(自 C++26 起为 constexpr) |
对元素进行排序并保持等价元素的顺序。如果抛出异常, * this 中元素的顺序是未指定的。
不会使任何引用或迭代器失效。
内容参数
复杂度给定 N 为 std:: distance ( begin ( ) , end ( ) ) :
1)
大约需要
N·log(N)
次比较(使用
operator
<
)。
2)
大约需要
N·log(N)
次比较函数
comp
的应用。
注释
std::sort
需要随机访问迭代器,因此不能用于
示例运行此代码 #include <functional>
#include <iostream>
#include <forward_list>
std::ostream& operator<<(std::ostream& ostr, const std::forward_list<int>& list)
{
for (const int i : list)
ostr << ' ' << i;
return ostr;
}
int main()
{
std::forward_list<int> list{8, 7, 5, 9, 0, 1, 3, 2, 6, 4};
std::cout << "initially: " << list << '\n';
list.sort();
std::cout << "ascending: " << list << '\n';
list.sort(std::greater<int>());
std::cout << "descending:" << list << '\n';
}
输出: initially: 8 7 5 9 0 1 3 2 6 4
ascending: 0 1 2 3 4 5 6 7 8 9
descending: 9 8 7 6 5 4 3 2 1 0
参阅
| |||||||||||