std::forward_list<T,Allocator>::sort
来自 cppreference.cn
< cpp | 容器 | forward_list
void sort(); |
(1) | (C++11 起) |
template< class Compare > void sort( Compare comp ); |
(2) | (C++11 起) |
对元素进行排序并保留等效元素的顺序。没有引用或迭代器会失效。
1) 使用 operator< 比较元素。
2) 使用 comp 比较元素。
如果抛出异常,则 *this 中元素的顺序未指定。
目录 |
[编辑] 参数
comp | - | 比较函数对象(即满足 Compare 要求的对象),如果第一个参数“小于”(即“排在”第二个参数之前),则返回 true。 比较函数的签名应等效于以下内容 bool cmp(const Type1& a, const Type2& b); 虽然签名不需要包含 const&,但函数不得修改传递给它的对象,并且必须能够接受 |
类型要求 | ||
-Compare 必须满足 Compare 的要求。 |
[编辑] 返回值
(无)
[编辑] 复杂度
给定 N 为 std::distance(begin(), end())
1) 使用 operator< 进行大约 N·log(N) 次比较。
2) 大约 N·log(N) 次应用比较函数 comp。
[编辑] 注意
std::sort 需要随机访问迭代器,因此不能与 forward_list
一起使用。此函数与 std::sort 的不同之处在于,它不要求 forward_list
的元素类型是可交换的,它会保留所有迭代器的值,并执行稳定的排序。
[编辑] 示例
运行此代码
#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
[编辑] 参阅
反转元素的顺序 (public member function) |