Namespaces
Variants
Views
Actions

Difference between revisions of "cpp/algorithm/ranges/merge"

From cppreference.com
< cpp‎ | algorithm‎ | ranges
m (break line)
m (fmt)
Line 2: Line 2:
 
{{cpp/algorithm/ranges/navbar}}
 
{{cpp/algorithm/ranges/navbar}}
 
{{dcl begin}}
 
{{dcl begin}}
{{dcl header | algorithm}}
+
{{dcl header|algorithm}}
{{dcl h | Call signature}}
+
{{dcl h|Call signature}}
{{dcl | num=1 | since=c++20 |1=
+
{{dcl|num=1|since=c++20|1=
 
template< std::input_iterator I1, std::sentinel_for<I1> S1,
 
template< std::input_iterator I1, std::sentinel_for<I1> S1,
 
           std::input_iterator I2, std::sentinel_for<I2> S2,
 
           std::input_iterator I2, std::sentinel_for<I2> S2,
 
           std::weakly_incrementable O, class Comp = ranges::less,
 
           std::weakly_incrementable O, class Comp = ranges::less,
 
           class Proj1 = std::identity, class Proj2 = std::identity >
 
           class Proj1 = std::identity, class Proj2 = std::identity >
requires std::mergeable<I1, I2, O, Comp, Proj1, Proj2>
+
requires std::mergeable<I1, I2, O, Comp, Proj1, Proj2>
 
constexpr merge_result<I1, I2, O>
 
constexpr merge_result<I1, I2, O>
          merge( I1 first1, S1 last1, I2 first2, S2 last2, O result, Comp comp = {},
+
    merge( I1 first1, S1 last1, I2 first2, S2 last2, O result, Comp comp = {},
                Proj1 proj1 = {}, Proj2 proj2 = {} );
+
          Proj1 proj1 = {}, Proj2 proj2 = {} );
 
}}
 
}}
{{dcl | num=2 | since=c++20 |1=
+
{{dcl|num=2|since=c++20|1=
 
template< ranges::input_range R1, ranges::input_range R2,
 
template< ranges::input_range R1, ranges::input_range R2,
 
           std::weakly_incrementable O, class Comp = ranges::less,
 
           std::weakly_incrementable O, class Comp = ranges::less,
 
           class Proj1 = std::identity, class Proj2 = std::identity >
 
           class Proj1 = std::identity, class Proj2 = std::identity >
requires std::mergeable<ranges::iterator_t<R1>, ranges::iterator_t<R2>,
+
requires std::mergeable<ranges::iterator_t<R1>, ranges::iterator_t<R2>,
          O, Comp, Proj1, Proj2>
+
        O, Comp, Proj1, Proj2>
 
constexpr merge_result<ranges::borrowed_iterator_t<R1>,
 
constexpr merge_result<ranges::borrowed_iterator_t<R1>,
 
                       ranges::borrowed_iterator_t<R2>, O>
 
                       ranges::borrowed_iterator_t<R2>, O>
          merge( R1&& r1, R2&& r2, O result, Comp comp = {},
+
    merge( R1&& r1, R2&& r2, O result, Comp comp = {},
                Proj1 proj1 = {}, Proj2 proj2 = {} );
+
          Proj1 proj1 = {}, Proj2 proj2 = {} );
 
}}
 
}}
{{dcl h | Helper types}}
+
{{dcl h|Helper types}}
{{dcl | num=3 | since=c++20 |1=
+
{{dcl|num=3|since=c++20|1=
template<class I1, class I2, class O>
+
template< class I1, class I2, class O >
 
using merge_result = ranges::in_in_out_result<I1, I2, O>;
 
using merge_result = ranges::in_in_out_result<I1, I2, O>;
 
}}
 
}}
 
{{dcl end}}
 
{{dcl end}}
  
Merges two ''sorted'' ranges {{tt|[first1, last1)}} and {{tt|[first2, last2)}} into one ''sorted'' range beginning at {{tt|result}}.
+
Merges two ''sorted'' ranges {{range|[first1|last1}} and {{range|first2|last2}} into one ''sorted'' range beginning at {{c|result}}.
  
A sequence is said to be ''sorted'' with respect to the comparator {{tt|comp}} if for any iterator {{tt|it}} pointing to the sequence and any non-negative integer {{tt|n}} such that {{tt|it + n}} is a valid iterator pointing to an element of the sequence, {{c|1=std::invoke(comp, std::invoke(proj2, *(it + n)), std::invoke(proj1, *it)))}} evaluates to {{c|false}}.
+
A sequence is said to be ''sorted'' with respect to the comparator {{c|comp}} if for any iterator {{tt|it}} pointing to the sequence and any non-negative integer {{tt|n}} such that {{tt|it + n}} is a valid iterator pointing to an element of the sequence, {{c|1=std::invoke(comp, std::invoke(proj2, *(it + n)), std::invoke(proj1, *it)))}} evaluates to {{c|false}}.
  
@1@ Elements are compared using the given binary comparison function {{tt|comp}}.
+
@1@ Elements are compared using the given binary comparison function {{c|comp}}.
  
@2@ Same as {{v|1}}, but uses {{tt|r1}} as the first range and {{tt|r2}} as the second range, as if using {{c|ranges::begin(r1)}} as {{tt|first1}}, {{c|ranges::end(r1)}} as {{tt|last1}}, {{c|ranges::begin(r2)}} as {{tt|first2}}, and {{c|ranges::end(r2)}} as {{tt|last2}}.
+
@2@ Same as {{v|1}}, but uses {{c|r1}} as the first range and {{c|r2}} as the second range, as if using {{c|ranges::begin(r1)}} as {{c|first1}}, {{c|ranges::end(r1)}} as {{c|last1}}, {{c|ranges::begin(r2)}} as {{c|first2}}, and {{c|ranges::end(r2)}} as {{c|last2}}.
  
 
The behavior is undefined if the destination range overlaps either of the input ranges (the input ranges may overlap each other).
 
The behavior is undefined if the destination range overlaps either of the input ranges (the input ranges may overlap each other).
Line 48: Line 48:
 
===Parameters===
 
===Parameters===
 
{{par begin}}
 
{{par begin}}
{{par | first1, last1 | the first input sorted range}}
+
{{par|first1, last1|the first input sorted range}}
{{par | first2, last2 | the second input sorted range}}
+
{{par|first2, last2|the second input sorted range}}
{{par | result | the beginning of the output range}}
+
{{par|result|the beginning of the output range}}
{{par | comp | comparison to apply to the projected elements}}
+
{{par|comp|comparison to apply to the projected elements}}
{{par | proj1 | projection to apply to the elements in the first range}}
+
{{par|proj1|projection to apply to the elements in the first range}}
{{par | proj2 | projection to apply to the elements in the second range}}
+
{{par|proj2|projection to apply to the elements in the second range}}
 
{{par end}}
 
{{par end}}
  
Line 60: Line 60:
  
 
===Complexity===
 
===Complexity===
At most {{c|N−1}} comparisons and applications of each projection, where
+
At most {{c|N − 1}} comparisons and applications of each projection, where
 
{{c|1= N = ranges::distance(first1, last1) + ranges::distance(first2, last12)}}.
 
{{c|1= N = ranges::distance(first1, last1) + ranges::distance(first2, last12)}}.
  
 
===Notes===
 
===Notes===
This algorithm performs a similar task as {{c|ranges::set_union}} does. Both consume two sorted input ranges and produce a sorted output with elements from both inputs. The difference between these two algorithms is with handling values from both input ranges which compare equivalent (see notes on {{named req|LessThanComparable}}). If any equivalent values appeared {{c|n}} times in the first range and {{c|m}} times in the second, {{lc|ranges::merge}} would output all {{c|n+m}} occurrences whereas {{lc|ranges::set_union}} would output {{c|max(n, m)}} ones only. So {{lc|ranges::merge}} outputs exactly {{c|N}} values and {{lc|ranges::set_union}} may produce fewer.
+
This algorithm performs a similar task as {{c|ranges::set_union}} does. Both consume two sorted input ranges and produce a sorted output with elements from both inputs. The difference between these two algorithms is with handling values from both input ranges which compare equivalent (see notes on {{named req|LessThanComparable}}). If any equivalent values appeared {{c|n}} times in the first range and {{c|m}} times in the second, {{lc|ranges::merge}} would output all {{c|n + m}} occurrences whereas {{lc|ranges::set_union}} would output {{c|max(n, m)}} ones only. So {{lc|ranges::merge}} outputs exactly {{c|N}} values and {{lc|ranges::set_union}} may produce fewer.
  
 
===Possible implementation===
 
===Possible implementation===
 
{{eq fun| 1=
 
{{eq fun| 1=
struct merge_fn {
+
struct merge_fn
     template< std::input_iterator I1, std::sentinel_for<I1> S1,
+
{
              std::input_iterator I2, std::sentinel_for<I2> S2,
+
     template<std::input_iterator I1, std::sentinel_for<I1> S1,
              std::weakly_incrementable O, class Comp = ranges::less,
+
            std::input_iterator I2, std::sentinel_for<I2> S2,
              class Proj1 = std::identity, class Proj2 = std::identity >
+
            std::weakly_incrementable O, class Comp = ranges::less,
 +
            class Proj1 = std::identity, class Proj2 = std::identity>
 
     requires std::mergeable<I1, I2, O, Comp, Proj1, Proj2>
 
     requires std::mergeable<I1, I2, O, Comp, Proj1, Proj2>
 
     constexpr ranges::merge_result<I1, I2, O>
 
     constexpr ranges::merge_result<I1, I2, O>
    operator()( I1 first1, S1 last1, I2 first2, S2 last2, O result, Comp comp = {},
+
        operator()(I1 first1, S1 last1, I2 first2, S2 last2, O result, Comp comp = {},
                Proj1 proj1 = {}, Proj2 proj2 = {} ) const {
+
                  Proj1 proj1 = {}, Proj2 proj2 = {}) const
         for (; !(first1 == last1 or first2 == last2); ++result) {
+
    {
 +
         for (; !(first1 == last1 or first2 == last2); ++result)
 +
        {
 
             if (std::invoke(comp, std::invoke(proj2, *first2), std::invoke(proj1, *first1)))
 
             if (std::invoke(comp, std::invoke(proj2, *first2), std::invoke(proj1, *first1)))
 
                 *result = *first2, ++first2;
 
                 *result = *first2, ++first2;
Line 85: Line 88:
 
         auto ret1 {ranges::copy(std::move(first1), std::move(last1), std::move(result))};
 
         auto ret1 {ranges::copy(std::move(first1), std::move(last1), std::move(result))};
 
         auto ret2 {ranges::copy(std::move(first2), std::move(last2), std::move(ret1.out))};
 
         auto ret2 {ranges::copy(std::move(first2), std::move(last2), std::move(ret1.out))};
         return { std::move(ret1.in), std::move(ret2.in), std::move(ret2.out) };
+
         return {std::move(ret1.in), std::move(ret2.in), std::move(ret2.out)};
 
     }
 
     }
  
     template< ranges::input_range R1, ranges::input_range R2, std::weakly_incrementable O,
+
     template<ranges::input_range R1, ranges::input_range R2, std::weakly_incrementable O,
              class Comp = ranges::less,
+
            class Comp = ranges::less,
              class Proj1 = std::identity, class Proj2 = std::identity >
+
            class Proj1 = std::identity, class Proj2 = std::identity>
 
     requires std::mergeable<ranges::iterator_t<R1>, ranges::iterator_t<R2>,
 
     requires std::mergeable<ranges::iterator_t<R1>, ranges::iterator_t<R2>,
 
             O, Comp, Proj1, Proj2>
 
             O, Comp, Proj1, Proj2>
 
     constexpr ranges::merge_result<ranges::borrowed_iterator_t<R1>,
 
     constexpr ranges::merge_result<ranges::borrowed_iterator_t<R1>,
 
               ranges::borrowed_iterator_t<R2>, O>
 
               ranges::borrowed_iterator_t<R2>, O>
    operator()( R1&& r1, R2&& r2, O result, Comp comp = {},
+
        operator()(R1&& r1, R2&& r2, O result, Comp comp = {},
                Proj1 proj1 = {}, Proj2 proj2 = {} ) const {
+
                  Proj1 proj1 = {}, Proj2 proj2 = {}) const
 +
    {
 
         return (*this)(ranges::begin(r1), ranges::end(r1),
 
         return (*this)(ranges::begin(r1), ranges::end(r1),
 
                       ranges::begin(r2), ranges::end(r2),
 
                       ranges::begin(r2), ranges::end(r2),
Line 104: Line 108:
 
};
 
};
  
inline constexpr merge_fn merge{};
+
inline constexpr merge_fn merge {};
 
}}
 
}}
  
 
===Example===
 
===Example===
 
{{example
 
{{example
| code=
+
|code=
#include <algorithm>
+
#include <algorithm>
 
#include <iostream>
 
#include <iostream>
 
#include <iterator>
 
#include <iterator>
 
#include <vector>
 
#include <vector>
  
void print(const auto& in1, const auto& in2, auto first, auto last) {
+
void print(const auto& in1, const auto& in2, auto first, auto last)
 +
{
 
     std::cout << "{ ";
 
     std::cout << "{ ";
 
     for (const auto& e : in1) { std::cout << e << ' '; }
 
     for (const auto& e : in1) { std::cout << e << ' '; }
Line 142: Line 147:
 
     print(in1, in2, out.cbegin(), out.cend());
 
     print(in1, in2, out.cbegin(), out.cend());
 
}
 
}
| output=
+
|output=
 
{ 1 2 3 4 5 } +
 
{ 1 2 3 4 5 } +
 
{ 3 4 5 6 7 } =
 
{ 3 4 5 6 7 } =
Line 154: Line 159:
 
===See also===
 
===See also===
 
{{dsc begin}}
 
{{dsc begin}}
{{dsc inc | cpp/algorithm/ranges/dsc inplace_merge}}
+
{{dsc inc|cpp/algorithm/ranges/dsc inplace_merge}}
{{dsc inc | cpp/algorithm/ranges/dsc is_sorted}}
+
{{dsc inc|cpp/algorithm/ranges/dsc is_sorted}}
{{dsc inc | cpp/algorithm/ranges/dsc set_union}}
+
{{dsc inc|cpp/algorithm/ranges/dsc set_union}}
{{dsc inc | cpp/algorithm/ranges/dsc sort}}
+
{{dsc inc|cpp/algorithm/ranges/dsc sort}}
{{dsc inc | cpp/algorithm/ranges/dsc stable_sort}}
+
{{dsc inc|cpp/algorithm/ranges/dsc stable_sort}}
{{dsc inc | cpp/algorithm/dsc merge}}
+
{{dsc inc|cpp/algorithm/dsc merge}}
 
{{dsc end}}
 
{{dsc end}}
  
 
{{langlinks|de|es|fr|it|ja|pt|ru|zh}}
 
{{langlinks|de|es|fr|it|ja|pt|ru|zh}}

Revision as of 03:24, 14 April 2023

 
 
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
(C++11)                (C++11)(C++11)

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
(C++11)
(C++17)
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
Numeric operations
(C++23)            
Operations on uninitialized storage
Return types
 
Defined in header <algorithm>
Call signature
template< std::input_iterator I1, std::sentinel_for<I1> S1,

          std::input_iterator I2, std::sentinel_for<I2> S2,
          std::weakly_incrementable O, class Comp = ranges::less,
          class Proj1 = std::identity, class Proj2 = std::identity >
requires std::mergeable<I1, I2, O, Comp, Proj1, Proj2>
constexpr merge_result<I1, I2, O>
    merge( I1 first1, S1 last1, I2 first2, S2 last2, O result, Comp comp = {},

           Proj1 proj1 = {}, Proj2 proj2 = {} );
(1) (since C++20)
template< ranges::input_range R1, ranges::input_range R2,

          std::weakly_incrementable O, class Comp = ranges::less,
          class Proj1 = std::identity, class Proj2 = std::identity >
requires std::mergeable<ranges::iterator_t<R1>, ranges::iterator_t<R2>,
         O, Comp, Proj1, Proj2>
constexpr merge_result<ranges::borrowed_iterator_t<R1>,
                       ranges::borrowed_iterator_t<R2>, O>
    merge( R1&& r1, R2&& r2, O result, Comp comp = {},

           Proj1 proj1 = {}, Proj2 proj2 = {} );
(2) (since C++20)
Helper types
template< class I1, class I2, class O >
using merge_result = ranges::in_in_out_result<I1, I2, O>;
(3) (since C++20)

Merges two sorted ranges [[first1last1) and [first2last2) into one sorted range beginning at result.

A sequence is said to be sorted with respect to the comparator comp if for any iterator it pointing to the sequence and any non-negative integer n such that it + n is a valid iterator pointing to an element of the sequence, std::invoke(comp, std::invoke(proj2, *(it + n)), std::invoke(proj1, *it))) evaluates to false.

1) Elements are compared using the given binary comparison function comp.
2) Same as (1), but uses r1 as the first range and r2 as the second range, as if using ranges::begin(r1) as first1, ranges::end(r1) as last1, ranges::begin(r2) as first2, and ranges::end(r2) as last2.

The behavior is undefined if the destination range overlaps either of the input ranges (the input ranges may overlap each other).

This merge function is stable, which means that for equivalent elements in the original two ranges, the elements from the first range (preserving their original order) precede the elements from the second range (preserving their original order).

The function-like entities described on this page are niebloids, that is:

In practice, they may be implemented as function objects, or with special compiler extensions.

Contents

Parameters

first1, last1 - the first input sorted range
first2, last2 - the second input sorted range
result - the beginning of the output range
comp - comparison to apply to the projected elements
proj1 - projection to apply to the elements in the first range
proj2 - projection to apply to the elements in the second range

Return value

{last1, last2, result_last}, where result_last is the end of the constructed range.

Complexity

At most N − 1 comparisons and applications of each projection, where N = ranges::distance(first1, last1) + ranges::distance(first2, last12).

Notes

This algorithm performs a similar task as ranges::set_union does. Both consume two sorted input ranges and produce a sorted output with elements from both inputs. The difference between these two algorithms is with handling values from both input ranges which compare equivalent (see notes on LessThanComparable). If any equivalent values appeared n times in the first range and m times in the second, ranges::merge would output all n + m occurrences whereas ranges::set_union would output max(n, m) ones only. So ranges::merge outputs exactly N values and ranges::set_union may produce fewer.

Possible implementation

struct merge_fn
{
    template<std::input_iterator I1, std::sentinel_for<I1> S1,
             std::input_iterator I2, std::sentinel_for<I2> S2,
             std::weakly_incrementable O, class Comp = ranges::less,
             class Proj1 = std::identity, class Proj2 = std::identity>
    requires std::mergeable<I1, I2, O, Comp, Proj1, Proj2>
    constexpr ranges::merge_result<I1, I2, O>
        operator()(I1 first1, S1 last1, I2 first2, S2 last2, O result, Comp comp = {},
                   Proj1 proj1 = {}, Proj2 proj2 = {}) const
    {
        for (; !(first1 == last1 or first2 == last2); ++result)
        {
            if (std::invoke(comp, std::invoke(proj2, *first2), std::invoke(proj1, *first1)))
                *result = *first2, ++first2;
            else
                *result = *first1, ++first1;
        }
        auto ret1 {ranges::copy(std::move(first1), std::move(last1), std::move(result))};
        auto ret2 {ranges::copy(std::move(first2), std::move(last2), std::move(ret1.out))};
        return {std::move(ret1.in), std::move(ret2.in), std::move(ret2.out)};
    }
 
    template<ranges::input_range R1, ranges::input_range R2, std::weakly_incrementable O,
             class Comp = ranges::less,
             class Proj1 = std::identity, class Proj2 = std::identity>
    requires std::mergeable<ranges::iterator_t<R1>, ranges::iterator_t<R2>,
             O, Comp, Proj1, Proj2>
    constexpr ranges::merge_result<ranges::borrowed_iterator_t<R1>,
              ranges::borrowed_iterator_t<R2>, O>
        operator()(R1&& r1, R2&& r2, O result, Comp comp = {},
                   Proj1 proj1 = {}, Proj2 proj2 = {}) const
    {
        return (*this)(ranges::begin(r1), ranges::end(r1),
                       ranges::begin(r2), ranges::end(r2),
                       std::move(result), std::move(comp),
                       std::move(proj1), std::move(proj2));
    }
};
 
inline constexpr merge_fn merge {};

Example

#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
 
void print(const auto& in1, const auto& in2, auto first, auto last)
{
    std::cout << "{ ";
    for (const auto& e : in1) { std::cout << e << ' '; }
    std::cout << "} +\n{ ";
    for (const auto& e : in2) { std::cout << e << ' '; }
    std::cout << "} =\n{ ";
    while (!(first == last)) { std::cout << *first++ << ' '; }
    std::cout << "}\n\n";
}
 
int main()
{
    std::vector<int> in1, in2, out;
 
    in1 = {1, 2, 3, 4, 5};
    in2 = {      3, 4, 5, 6, 7};
    out.resize(in1.size() + in2.size());
    const auto ret = std::ranges::merge(in1, in2, out.begin());
    print(in1, in2, out.begin(), ret.out);
 
    in1 = {1, 2, 3, 4, 5, 5, 5};
    in2 = {      3, 4, 5, 6, 7};
    out.clear();
    out.reserve(in1.size() + in2.size());
    std::ranges::merge(in1, in2, std::back_inserter(out));
    print(in1, in2, out.cbegin(), out.cend());
}

Output:

{ 1 2 3 4 5 } +
{ 3 4 5 6 7 } =
{ 1 2 3 3 4 4 5 5 6 7 }
 
{ 1 2 3 4 5 5 5 } +
{ 3 4 5 6 7 } =
{ 1 2 3 3 4 4 5 5 5 5 6 7 }

See also

merges two ordered ranges in-place
(niebloid)[edit]
checks whether a range is sorted into ascending order
(niebloid)[edit]
computes the union of two sets
(niebloid)[edit]
sorts a range into ascending order
(niebloid)[edit]
sorts a range of elements while preserving order between equal elements
(niebloid)[edit]
merges two sorted ranges
(function template) [edit]