Namespaces
Variants

std::ranges:: inplace_merge

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
Constrained algorithms
All names in this menu belong to namespace std::ranges
Non-modifying sequence operations
Modifying sequence operations
Partitioning operations
Sorting operations
Binary search operations (on sorted ranges)
Set operations (on sorted ranges)
Heap operations
Minimum/maximum operations
Permutation operations
Fold operations
Operations on uninitialized storage
Return types
定义于头文件 <algorithm>
调用签名
template < std:: bidirectional_iterator I, std:: sentinel_for < I > S,

class Comp = ranges:: less , class Proj = std:: identity >
requires std:: sortable < I, Comp, Proj >
I inplace_merge ( I first, I middle, S last,

Comp comp = { } , Proj proj = { } ) ;
(1) (C++20 起)
(C++26 起为 constexpr)
template < ranges:: bidirectional_range R, class Comp = ranges:: less ,

class Proj = std:: identity >
requires std:: sortable < ranges:: iterator_t < R > , Comp, Proj >
ranges:: borrowed_iterator_t < R >
inplace_merge ( R && r, ranges:: iterator_t < R > middle,

Comp comp = { } , Proj proj = { } ) ;
(2) (C++20 起)
(C++26 起为 constexpr)

将两个连续的 已排序 范围 [ first , middle ) [ middle , last ) 合并为一个 已排序 范围 [ first , last )

一个序列被称为相对于比较器 comp 和投影 proj 已排序的 ,如果对于任何指向该序列的迭代器 it 和任何非负整数 n ,使得 it + n 是指向序列元素的有效迭代器, std:: invoke ( comp, std:: invoke ( proj, * ( it + n ) ) , std:: invoke ( proj, * it ) ) ) 的求值结果为 false

此合并函数是 稳定 的,这意味着对于原始两个范围中的等价元素,来自第一个范围的元素(保持其原始顺序)会先于来自第二个范围的元素(保持其原始顺序)。

1) 元素通过给定的二元比较函数 comp 和投影对象 proj 进行比较,且范围必须按照相同的标准进行排序。
2) (1) 相同,但使用 r 作为范围,如同以 ranges:: begin ( r ) 作为 first ,并以 ranges:: end ( r ) 作为 last

本页面描述的函数式实体是 算法函数对象 (非正式称为 niebloids ),即:

目录

参数

first - 第一个有序范围的起始位置
middle - 第一个范围的结束位置与第二个范围的起始位置
last - 第二个有序范围的结束位置
r - 需要原地合并的元素范围
comp - 应用于投影元素的比较器
proj - 应用于范围内元素的投影器

返回值

一个等于 last 的迭代器。

复杂度

如果存在额外的内存缓冲区,则恰好需要 N − 1 次比较,其中 N = ranges:: distance ( first, last ) 。否则,需要 𝓞(N•log(N)) 次比较。在两种情况下,投影次数均为比较次数的两倍。

注释

此函数尝试分配临时缓冲区。若分配失败,则选择效率较低的算法。

功能测试 标准 功能
__cpp_lib_constexpr_algorithms 202306L (C++26) constexpr 稳定排序

可能的实现

此实现仅展示在无额外内存可用时采用的较慢算法。另请参阅 MSVC STL libstdc++ 中的实现。

struct inplace_merge_fn
{
    template<std::bidirectional_iterator I, std::sentinel_for<I> S,
             class Comp = ranges::less, class Proj = std::identity>
    requires std::sortable<I, Comp, Proj>
    constexpr I operator()(I first, I middle, S last, Comp comp = {}, Proj proj = {}) const
    {
        I last_it = ranges::next(middle, last);
        inplace_merge_slow(first, middle, last_it,
                           ranges::distance(first, middle),
                           ranges::distance(middle, last_it),
                           std::ref(comp), std::ref(proj));
        return last_it;
    }
    template<ranges::bidirectional_range R, class Comp = ranges::less,
             class Proj = std::identity>
    requires std::sortable<ranges::iterator_t<R>, Comp, Proj>
    constexpr ranges::borrowed_iterator_t<R>
        operator()(R&& r, ranges::iterator_t<R> middle,
                   Comp comp = {}, Proj proj = {}) const
    {
        return (*this)(ranges::begin(r), std::move(middle), ranges::end(r),
                       std::move(comp), std::move(proj));
    }
private:
    template<class I, class Comp, class Proj>
    static constexpr void inplace_merge_slow(I first, I middle, I last,
                                             std::iter_difference_t<I> n1,
                                             std::iter_difference_t<I> n2,
                                             Comp comp, Proj proj)
    {
        if (n1 == 0 || n2 == 0)
            return;
        if (n1 + n2 == 2 && comp(proj(*middle), proj(*first)))
        {
            ranges::iter_swap(first, middle);
            return;
        }
        I cut1 = first, cut2 = middle;
        std::iter_difference_t<I> d1{}, d2{};
        if (n1 > n2)
        {
            d1 = n1 / 2;
            ranges::advance(cut1, d1);
            cut2 = ranges::lower_bound(middle, last, *cut1,
                                       std::ref(comp), std::ref(proj));
            d2 = ranges::distance(middle, cut2);
        }
        else
        {
            d2 = n2 / 2;
            ranges::advance(cut2, d2);
            cut1 = ranges::upper_bound(first, middle, *cut2,
                                       std::ref(comp), std::ref(proj));
            d1 = ranges::distance(first, cut1);
        }
        I new_middle = ranges::rotate(cut1, middle, cut2);
        inplace_merge_slow(first, cut1, new_middle, d1, d2,
                           std::ref(comp), std::ref(proj));
        inplace_merge_slow(new_middle, cut2, last, n1 - d1, n2 - d2,
                           std::ref(comp), std::ref(proj));
    }
}<

示例

#include <algorithm>
#include <complex>
#include <functional>
#include <iostream>
#include <iterator>
#include <vector>
void print(auto const& v, auto const& rem, int middle = -1)
{
    for (int i{}; auto n : v)
        std::cout << (i++ == middle ? "│ " : "") << n << ' ';
    std::cout << rem << '\n';
}
template<std::random_access_iterator I, std::sentinel_for<I> S>
requires std::sortable<I>
void merge_sort(I first, S last)
{
    if (last - first > 1)
    {
        I middle{first + (last - first) / 2};
        merge_sort(first, middle);
        merge_sort(middle, last);
        std::ranges::inplace_merge(first, middle, last);
    }
}
int main()
{
    // 自定义归并排序演示
    std::vector v{8, 2, 0, 4, 9, 8, 1, 7, 3};
    print(v, ": before sort");
    merge_sort(v.begin(), v.end());
    print(v, ": after sort\n");
    // 使用比较函数对象和投影进行合并
    using CI = std::complex<int>;
    std::vector<CI> r{{0,1}, {0,2}, {0,3}, {1,1}, {1,2}};
    const auto middle{std::ranges::next(r.begin(), 3)};
    auto comp{std::ranges::less{}};
    auto proj{[](CI z) { return z.imag(); }};
    print(r, ": before merge", middle - r.begin());
    std::ranges::inplace_merge(r, middle, comp, proj);
    print(r, ": after merge");
}

输出:

8 2 0 4 9 8 1 7 3 : before sort
0 1 2 3 4 7 8 8 9 : after sort
(0,1) (0,2) (0,3) │ (1,1) (1,2) : before merge
(0,1) (1,1) (0,2) (1,2) (0,3) : after merge

参见

合并两个已排序范围
(算法函数对象)
计算两个集合的并集
(算法函数对象)
检查范围是否按升序排序
(算法函数对象)
将范围按升序排序
(算法函数对象)
就地合并两个有序范围
(函数模板)