std::forward_list sort() 方法
- 自 C++11 起
// (1) Non const version only
void sort();
// (2) Non const version only
template< class Compare >
void sort( Compare comp );
以升序对元素进行排序。
相等元素的顺序保持不变。
- (1) 使用
operator<
比较元素。 - (2) 使用给定的比较函数
comp
。
如果抛出异常,*this
中元素的顺序不确定。
参数
-
comp
- 比较函数对象,如果第一个参数小于第二个,则返回true
。谓词函数的签名应等同于以下内容
bool cmp( const Type1& a, const Type2& b )
虽然签名不需要包含
const&
,但函数不得修改传递给它的对象,并且必须能够接受Type1
和Type2
类型的所有值(可能为const),无论其值类别如何(因此,不允许使用Type1&
,除非对于Type1
移动等同于复制,否则也不允许使用Type1
(自 C++11 起))。Type1
和Type2
的类型必须使得forward_list<T, Allocator>::const_iterator
类型的对象可以被解引用,然后隐式转换为两者。
返回值
(无)
复杂度
大约进行N log N
次比较,其中N
是列表中元素的数量。
异常
(无)
备注
std::sort
需要RandomAccessIterator
,因此不能与forward_list
一起使用。
此函数与std::sort
的不同之处在于,它不要求forward_list
的元素类型为Swappable
,它保留所有迭代器的值,并执行稳定排序。
示例
#include <iostream>
#include <functional>
#include <forward_list>
std::ostream& operator<<(std::ostream& ostr, const std::forward_list<int>& list)
{
for (auto &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 << "before: " << list << "\n";
list.sort();
std::cout << "ascending: " << list << "\n";
list.sort(std::greater<int>());
std::cout << "descending: " << list << "\n";
}
before: 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