在线文档教程
C++
容器 | Containers

std::forward_list::sort

STD:向前[医]清单::排序

void sort((1)(since C++11)
template< class Compare > void sort( Compare comp (2)(since C++11)

按升序排列元素。保持等量元素的顺序。第一个版本使用operator<为了比较元素,第二个版本使用给定的比较函数。comp...

如果引发异常,则*this没有具体说明。

参数

comp-comparison function object (i.e. an object that satisfies the requirements of Compare) which returns ​true if the first argument is less than (i.e. is ordered before) the second. The signature of the comparison function should be equivalent to the following: bool cmp(const Type1 &a, const Type2 &b The signature does not need to have const &, but the function object must not modify the objects passed to it. The types Type1 and Type2 must be such that an object of type forward_list::const_iterator can be dereferenced and then implicitly converted to both of them. ​

返回值

%280%29

复杂性

N log N比较,其中N是列表中元素的数量。

注记

std::sort需要随机访问迭代器,因此不能与forward_list这个功能也不同于std::sort的元素类型。forward_list要可交换,保留所有迭代器的值,并执行稳定的排序。

二次

#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.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

http://en.cppreference.com/w/cpp/container/Forward[医]列表/排序