Namespaces
Variants

std:: partial_sort

From cppreference.net
Algorithm library
Constrained algorithms and algorithms on ranges (C++20)
Constrained algorithms, e.g. ranges::copy , ranges::sort , ...
Execution policies (C++17)
Non-modifying sequence operations
Batch operations
(C++17)
Search operations
Modifying sequence operations
Copy operations
(C++11)
(C++11)
Swap operations
Transformation operations
Generation operations
Removing operations
Order-changing operations
(until C++17) (C++11)
(C++20) (C++20)
Sampling operations
(C++17)

Sorting and related operations
Partitioning operations
Sorting operations
Binary search operations
(on partitioned ranges)
Set operations (on sorted ranges)
Merge operations (on sorted ranges)
Heap operations
Minimum/maximum operations
Lexicographical comparison operations
Permutation operations
C library
Numeric operations
Operations on uninitialized memory
定义于头文件 <algorithm>
template < class RandomIt >
void partial_sort ( RandomIt first, RandomIt middle, RandomIt last ) ;
(1) (自 C++20 起为 constexpr)
template < class ExecutionPolicy, class RandomIt >

void partial_sort ( ExecutionPolicy && policy,

RandomIt first, RandomIt middle, RandomIt last ) ;
(2) (自 C++17 起)
template < class RandomIt, class Compare >

void partial_sort ( RandomIt first, RandomIt middle, RandomIt last,

Compare comp ) ;
(3) (自 C++20 起为 constexpr)
template < class ExecutionPolicy, class RandomIt, class Compare >

void partial_sort ( ExecutionPolicy && policy,
RandomIt first, RandomIt middle, RandomIt last,

Compare comp ) ;
(4) (自 C++17 起)

重新排列元素,使得范围 [ first , middle ) 包含范围 [ first , last ) 中已排序的 middle − first 个最小元素。

相等元素的顺序不保证会被保留。范围 [ middle , last ) 中剩余元素的顺序是未指定的。

1) 元素按照 operator < (C++20 前) std:: less { } (C++20 起) 进行排序。
3) 元素根据 comp 进行排序。
2,4) (1,3) 相同,但根据 policy 执行。
这些重载仅在满足以下所有条件时参与重载决议:

std:: is_execution_policy_v < std:: decay_t < ExecutionPolicy >> true

(C++20 前)

std:: is_execution_policy_v < std:: remove_cvref_t < ExecutionPolicy >> true

(C++20 起)

若满足以下任一条件,则行为未定义:

  • [ first , middle ) [ middle , last ) 不是有效的 范围
(C++11 前)
(C++11 起)

目录

参数

first, last - 定义待重排元素 范围 的迭代器对
middle - 范围 [ first , middle ) 将包含已排序元素
policy - 要使用的 执行策略
comp - 比较函数对象(即满足 Compare 要求的对象),若第一参数 小于 (即先序于)第二参数则返回 ​ true

比较函数的签名应等价于如下形式:

bool cmp ( const Type1 & a, const Type2 & b ) ;

虽然签名不必包含 const & ,函数也不能修改传递给它的对象,而且必须能够接受(可能为 const 的)类型 Type1 Type2 的所有值,与 值类别 无关(从而不允许 Type1& ,亦不允许 Type1 ,除非 Type1 的移动等价于复制 (C++11 起) )。
类型 Type1 Type2 必须使得 RandomIt 类型的对象能在解引用后隐式转换到这两个类型。 ​

类型要求
-
RandomIt 必须满足 LegacyRandomAccessIterator 的要求。
-
Compare 必须满足 Compare 的要求。

复杂度

给定 M middle - first N last - first

1,2) 大约需要 N·log(M) 次比较,使用 operator < (C++20 前) std:: less { } (C++20 起)
3,4) 大约需要 N·log(M) 次比较器 comp 的应用。

异常

带有名为 ExecutionPolicy 模板参数的重载按以下方式报告错误:

  • 如果作为算法一部分调用的函数执行抛出异常,且 ExecutionPolicy 是某个 标准策略 ,则调用 std::terminate 。对于任何其他 ExecutionPolicy ,其行为由实现定义。
  • 如果算法无法分配内存,则抛出 std::bad_alloc

可能的实现

另请参阅 libstdc++ libc++ 中的实现。

partial_sort (1)
template<typename RandomIt>
constexpr //< since C++20
void partial_sort(RandomIt first, RandomIt middle, RandomIt last)
{
    typedef typename std::iterator_traits<RandomIt>::value_type VT;
    std::partial_sort(first, middle, last, std::less<VT>());
}
partial_sort (3)
namespace impl
{
    template<typename RandomIt, typename Compare>
    constexpr //< since C++20
    void sift_down(RandomIt first, RandomIt last, const Compare& comp)
    {
        // 下沉位于“first”的元素
        const auto length = static_cast<std::size_t>(last - first);
        std::size_t current = 0;
        std::size_t next = 2;
        while (next < length)
        {
            if (comp(*(first + next), *(first + (next - 1))))
                --next;
            if (!comp(*(first + current), *(first + next)))
                return;
            std::iter_swap(first + current, first + next);
            current = next;
            next = 2 * current + 2;
        }
        --next;
        if (next < length && comp(*(first + current), *(first + next)))
            std::iter_swap(first + current, first + next);
    }
    template<typename RandomIt, typename Compare>
    constexpr //< since C++20
    void heap_select(RandomIt first, RandomIt middle, RandomIt last, const Compare& comp)
    {
        std::make_heap(first, middle, comp);
        for (auto i = middle; i != last; ++i)
        {
            if (comp(*i, *first))
            {
                std::iter_swap(first, i);
                sift_down(first, middle, comp);
            }
        }
    }
} // namespace impl
template<typename RandomIt, typename Compare>
constexpr //< since C++20
void partial_sort(RandomIt first, RandomIt middle, RandomIt last, Compare comp)
{
    impl::heap_select(first, middle, last, comp);
    std::sort_heap(first, middle, comp);
}

注释

算法

采用的算法通常使用 堆选择 来选取最小元素,并使用 堆排序 对堆中已选元素进行升序排序。

为了选择元素,使用堆结构(参见 )。例如,当使用 operator < 作为比较函数时,采用 最大堆 来选取 middle − first 个最小元素。

堆排序 在选择操作后用于对 [ first , middle ) 范围内的选定元素进行排序(参见 std::sort_heap )。

用途说明

std::partial_sort 算法旨在用于处理 [ first , middle ) 范围内 较小常量数量 的选定元素。

示例

#include <algorithm>
#include <array>
#include <functional>
#include <iostream>
void print(const auto& s, int middle)
{
    for (int a : s)
        std::cout << a << ' ';
    std::cout << '\n';
    if (middle > 0)
    {
        while (middle-- > 0)
            std::cout << "--";
        std::cout << '^';
    }
    else if (middle < 0)
    {
        for (auto i = s.size() + middle; --i; std::cout << "  ")
        {}
        for (std::cout << '^'; middle++ < 0; std::cout << "--")
        {}
    }
    std::cout << '\n';
};
int main()
{
    std::array<int, 10> s{5, 7, 4, 2, 8, 6, 1, 9, 0, 3};
    print(s, 0);
    std::partial_sort(s.begin(), s.begin() + 3, s.end());
    print(s, 3);
    std::partial_sort(s.rbegin(), s.rbegin() + 4, s.rend());
    print(s, -4);
    std::partial_sort(s.rbegin(), s.rbegin() + 5, s.rend(), std::greater{});
    print(s, -5);
}

可能的输出:

5 7 4 2 8 6 1 9 0 3
0 1 2 7 8 6 5 9 4 3
------^
4 5 6 7 8 9 3 2 1 0
          ^--------
4 3 2 1 0 5 6 7 8 9
        ^----------

缺陷报告

下列行为变更缺陷报告被追溯应用于先前发布的C++标准。

缺陷报告 适用范围 发布时行为 正确行为
P0896R4 C++98 [ first , middle ) [ middle , last )
未被要求必须是有效范围
若任一范围无效
则行为未定义

参见

对给定范围进行部分排序,确保其按给定元素划分
(函数模板)
复制并部分排序元素范围
(函数模板)
对元素范围进行排序,同时保持相等元素间的顺序
(函数模板)
将范围按升序排序
(函数模板)
对范围的前N个元素进行排序
(算法函数对象)