首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

std::forward_list::sort

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<T,Allocator>::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要可交换,保留所有迭代器的值,并执行稳定的排序。

二次

代码语言:javascript
复制
#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";
}

二次

产出:

二次

代码语言:javascript
复制
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

二次

代码语言:txt
复制
 ? cppreference.com

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

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com