在线文档教程
C++
算法 | Algorithm

std::stable_sort

性病:稳定[医]排序

Defined in header
template< class RandomIt > void stable_sort( RandomIt first, RandomIt last (1)
template< class ExecutionPolicy, class RandomIt > void stable_sort( ExecutionPolicy&& policy, RandomIt first, RandomIt last (2)(since C++17)
template< class RandomIt, class Compare > void stable_sort( RandomIt first, RandomIt last, Compare comp (3)
template< class ExecutionPolicy, class RandomIt, class Compare > void stable_sort( ExecutionPolicy&& policy, RandomIt first, RandomIt last, Compare comp (4)(since C++17)

排序范围内的元素[first, last)按升序排列。平等元素的顺序得到保证。

1%29个元素的比较operator<...

使用给定的比较函数对3%29个元素进行了比较。comp...

2,4%29与%281,3%29相同,但根据policy这些过载不参与过载解决,除非std::is_execution_policy_v<std::decay_t<ExecutionPolicy>>是真的

参数

first, last-the range of elements to sort
policy-the execution policy to use. See execution policy for details.
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 RandomIt can be dereferenced and then implicitly converted to both of them. ​

类型要求

---。

-取消引用的随机数的类型必须符合可移动分配和移动可建的要求。

返回值

%280%29

复杂性

O%28N·log 2%28N%29%29N =std::distance(first, last)的应用cmp如果有额外的内存可用,则复杂度为O%28N·log%28N%29%29。

例外

带有名为ExecutionPolicy报告错误如下:

  • 如果执行作为算法一部分调用的函数,则引发异常ExecutionPolicy是其中之一标准政策,,,std::terminate叫做。对于任何其他人ExecutionPolicy,行为是由实现定义的。

  • 如果算法不能分配内存,std::bad_alloc被扔了。

注记

此函数尝试为要排序的序列分配大小相等的临时缓冲区。如果分配失败,则选择效率较低的算法。

二次

#include <algorithm> #include <iostream> #include <string> #include <vector> struct Employee { Employee(int age, std::string name) : age(age), name(name) { } int age; std::string name; // Does not particpate in comparisons }; bool operator<(const Employee &lhs, const Employee &rhs) { return lhs.age < rhs.age; } int main() { std::vector<Employee> v = { Employee(108, "Zaphod"), Employee(32, "Arthur"), Employee(108, "Ford"), }; std::stable_sort(v.begin(), v.end() for (const Employee &e : v) { std::cout << e.age << ", " << e.name << '\n'; } }

二次

产出:

二次

32, Arthur 108, Zaphod 108, Ford

二次

另见

partial_sortsorts the first N elements of a range (function template)
sortsorts a range into ascending order (function template)

© cppreference.com

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

http://en.cppreference.com/w/cpp/Algorithm/STATURE[医]排序