Namespaces
Variants

std:: 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)
merge
Heap operations
Minimum/maximum operations
Lexicographical comparison operations
Permutation operations
C library
Numeric operations
Operations on uninitialized memory
ヘッダーで定義 <algorithm>
template < class InputIt1, class InputIt2, class OutputIt >

OutputIt merge ( InputIt1 first1, InputIt1 last1,
InputIt2 first2, InputIt2 last2,

OutputIt d_first ) ;
(1) (constexpr since C++20)
template < class ExecutionPolicy,

class ForwardIt1, class ForwardIt2, class ForwardIt3 >
ForwardIt3 merge ( ExecutionPolicy && policy,
ForwardIt1 first1, ForwardIt1 last1,
ForwardIt2 first2, ForwardIt2 last2,

ForwardIt3 d_first ) ;
(2) (since C++17)
template < class InputIt1, class InputIt2,

class OutputIt, class Compare >
OutputIt merge ( InputIt1 first1, InputIt1 last1,
InputIt2 first2, InputIt2 last2,

OutputIt d_first, Compare comp ) ;
(3) (constexpr since C++20)
template < class ExecutionPolicy,

class ForwardIt1, class ForwardIt2,
class ForwardIt3, class Compare >
ForwardIt3 merge ( ExecutionPolicy && policy,
ForwardIt1 first1, ForwardIt1 last1,
ForwardIt2 first2, ForwardIt2 last2,

ForwardIt3 d_first, Compare comp ) ;
(4) (since C++17)

二つのソート済み範囲 [ first1 , last1 ) [ first2 , last2 ) d_first から始まる一つのソート済み範囲にマージします。

1) [ first1 , last1 ) または [ first2 , last2 ) ソート済み でない場合 operator < (C++20以前) std:: less { } (C++20以降) に関して、動作は未定義です。
3) first1 , last1 ) または [ first2 , last2 ) 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以降)

このマージ関数は安定しています。つまり、元の2つの範囲で等価な要素の場合、最初の範囲の要素(元の順序を保持)が2番目の範囲の要素(元の順序を保持)よりも前に配置されます。

出力範囲が [ first1 , last1 ) または [ first2 , last2 ) と重なる場合、動作は未定義です。

目次

翻訳の説明: - 「Contents」を「目次」に翻訳しました - C++関連の専門用語(Parameters、Return value、Complexity、Exceptions、Possible implementation、Notes、Example、Defect reports、See also)は原文のまま保持しました - HTMLタグ、属性、クラス名、IDなどは一切変更していません - 数値や書式設定は完全に保持されています

パラメータ

first1, last1 - マージする要素の最初の 範囲 を定義するイテレータのペア
first2, last2 - マージする要素の2番目の 範囲 を定義するイテレータのペア
d_first - 出力先範囲の先頭
policy - 使用する 実行ポリシー
comp - 比較関数オブジェクト(つまり Compare の要件を満たすオブジェクト)。最初の引数が2番目の引数より 小さい (つまり 前に順序付けられる )場合に​ true を返す。

比較関数のシグネチャは以下と同等であるべき:

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

シグネチャが const & を持つ必要はないが、関数は渡されたオブジェクトを変更してはならず、 値カテゴリ に関係なく(したがって Type1& は許可されない Type1 Type1 に対してムーブがコピーと等価でない限り許可されない (C++11以降) )、型 Type1 Type2 のすべての値を受け入れられなければならない。
Type1 Type2 は、 InputIt1 InputIt2 型のオブジェクトが間接参照可能であり、暗黙的に Type1 Type2 の両方に変換可能でなければならない。 ​

型要件
-
InputIt1, InputIt2 LegacyInputIterator の要件を満たさなければならない。
-
ForwardIt1, ForwardIt2, ForwardIt3 LegacyForwardIterator の要件を満たさなければならない。
-
OutputIt LegacyOutputIterator の要件を満たさなければならない。
-
Compare Compare の要件を満たさなければならない。

戻り値

コピーされた最後の要素の次の要素を指す出力イテレータ。

計算量

N 1 std:: distance ( first1, last1 ) として、 N 2 std:: distance ( first2, last2 ) として定義する:

1) 最大で N 1 +N 2 -1 回の比較を operator < (C++20以前) std:: less { } (C++20以降) を使用して行う。
2) O(N 1 +N 2 ) 回の比較を使用して operator < (C++20まで) std:: less { } (C++20以降)
3) 最大で N 1 +N 2 -1 回の比較関数 comp の適用。
4) O(N 1 +N 2 ) 比較関数 comp の適用回数

例外

ExecutionPolicy という名前のテンプレートパラメータを持つオーバーロードは、 以下のようにエラーを報告します:

  • アルゴリズムの一部として呼び出された関数の実行が例外をスローした場合、 ExecutionPolicy 標準ポリシー のいずれかであるとき、 std::terminate が呼び出されます。それ以外の ExecutionPolicy については、動作は実装定義です。
  • アルゴリズムがメモリの確保に失敗した場合、 std::bad_alloc がスローされます。

実装例

実装例については libstdc++ および libc++ も参照してください。

merge (1)
template<class InputIt1, class InputIt2, class OutputIt>
OutputIt merge(InputIt1 first1, InputIt1 last1,
               InputIt2 first2, InputIt2 last2,
               OutputIt d_first)
{
    for (; first1 != last1; ++d_first)
    {
        if (first2 == last2)
            return std::copy(first1, last1, d_first);
        if (*first2 < *first1)
        {
            *d_first = *first2;
            ++first2;
        }
        else
        {
            *d_first = *first1;
            ++first1;
        }
    }
    return std::copy(first2, last2, d_first);
}
merge (3)
template<class InputIt1, class InputIt2,
         class OutputIt, class Compare>
OutputIt merge(InputIt1 first1, InputIt1 last1,
               InputIt2 first2, InputIt2 last2,
               OutputIt d_first, Compare comp)
{
    for (; first1 != last1; ++d_first)
    {
        if (first2 == last2)
            return std::copy(first1, last1, d_first);
        if (comp(*first2, *first1))
        {
            *d_first = *first2;
            ++first2;
        }
        else
        {
            *d_first = *first1;
            ++first1;
        }
    }
    return std::copy(first2, last2, d_first);
}
(注:HTMLタグ、属性、
タグ内のテキスト、C++固有の用語は翻訳せず、元のフォーマットを保持しています)

注記

このアルゴリズムは std:: set_union と同様の処理を実行します。両アルゴリズムとも2つのソート済み入力範囲を消費し、両入力の要素を含むソート済み出力を生成します。これらのアルゴリズムの違いは、両方の入力範囲から等価と比較される値( LessThanComparable に関する注記を参照)の扱いにあります。等価な値が最初の範囲に n 回、2番目の範囲に m 回現れた場合、 std::merge n + m 個の全ての出現を出力しますが、 std::set_union std:: max ( n, m ) 個のみを出力します。したがって std::merge は正確に std:: distance ( first1, last1 ) + std:: distance ( first2, last2 ) 個の値を出力しますが、 std::set_union はより少ない数を出力する可能性があります。

#include <algorithm>
#include <functional>
#include <iostream>
#include <iterator>
#include <random>
#include <vector>
auto print = [](const auto rem, const auto& v)
{
    std::cout << rem;
    std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " "));
    std::cout << '\n';
};
int main()
{
    // ベクターに乱数を格納
    std::random_device rd;
    std::mt19937 mt(rd());
    std::uniform_int_distribution<> dis(0, 9);
    std::vector<int> v1(10), v2(10);
    std::generate(v1.begin(), v1.end(), std::bind(dis, std::ref(mt)));
    std::generate(v2.begin(), v2.end(), std::bind(dis, std::ref(mt)));
    print("Originally:\nv1: ", v1);
    print("v2: ", v2);
    std::sort(v1.begin(), v1.end());
    std::sort(v2.begin(), v2.end());
    print("After sorting:\nv1: ", v1);
    print("v2: ", v2);
    // マージ
    std::vector<int> dst;
    std::merge(v1.begin(), v1.end(), v2.begin(), v2.end(), std::back_inserter(dst));
    print("After merging:\ndst: ", dst);
}

出力例:

Originally:
v1: 2 6 5 7 4 2 2 6 7 0
v2: 8 3 2 5 0 1 9 6 5 0
After sorting:
v1: 0 2 2 2 4 5 6 6 7 7
v2: 0 0 1 2 3 5 5 6 8 9
After merging:
dst: 0 0 0 1 2 2 2 2 3 4 5 5 5 6 6 6 7 7 8 9

不具合報告

以下の動作変更の欠陥報告書は、以前に公開されたC++規格に対して遡及的に適用されました。

DR 適用対象 公開時の動作 正しい動作
LWG 780 C++98 merge操作は定義されていなかった 定義済み

関連項目

二つの整列された範囲をその場でマージする
(関数テンプレート)
(C++11)
範囲が昇順にソートされているかどうかをチェックする
(関数テンプレート)
二つの集合の和集合を計算する
(関数テンプレート)
範囲を昇順にソートする
(関数テンプレート)
等しい要素間の順序を保ちながら範囲の要素をソートする
(関数テンプレート)
二つのソートされた範囲をマージする
(アルゴリズム関数オブジェクト)