跳到主要内容

std::forward_list sort() 方法

// (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&,但函数不得修改传递给它的对象,并且必须能够接受Type1Type2类型的所有值(可能为const),无论其值类别如何(因此,不允许使用Type1&,除非对于Type1移动等同于复制,否则也不允许使用Type1 (自 C++11 起))。

    Type1Type2的类型必须使得forward_list<T, Allocator>::const_iterator类型的对象可以被解引用,然后隐式转换为两者。

返回值

(无)

复杂度

大约进行N log N次比较,其中N是列表中元素的数量。

异常

(无)

备注

std::sort需要RandomAccessIterator,因此不能与forward_list一起使用。
此函数与std::sort的不同之处在于,它不要求forward_list的元素类型为Swappable,它保留所有迭代器的值,并执行稳定排序

示例

Main.cpp
#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
本文源自此 CppReference 页面。它可能为了改进或编辑者偏好而进行了修改。单击“编辑此页面”可查看对本文档进行的所有更改。
悬停查看原始许可证。

std::forward_list sort() 方法

// (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&,但函数不得修改传递给它的对象,并且必须能够接受Type1Type2类型的所有值(可能为const),无论其值类别如何(因此,不允许使用Type1&,除非对于Type1移动等同于复制,否则也不允许使用Type1 (自 C++11 起))。

    Type1Type2的类型必须使得forward_list<T, Allocator>::const_iterator类型的对象可以被解引用,然后隐式转换为两者。

返回值

(无)

复杂度

大约进行N log N次比较,其中N是列表中元素的数量。

异常

(无)

备注

std::sort需要RandomAccessIterator,因此不能与forward_list一起使用。
此函数与std::sort的不同之处在于,它不要求forward_list的元素类型为Swappable,它保留所有迭代器的值,并执行稳定排序

示例

Main.cpp
#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
本文源自此 CppReference 页面。它可能为了改进或编辑者偏好而进行了修改。单击“编辑此页面”可查看对本文档进行的所有更改。
悬停查看原始许可证。