# std::ranges::merge, std::ranges::merge_result

> C++ Atlas: `cppatlas.com/w/cpp/algorithm/ranges/merge` | Source: https://en.cppreference.com/w/cpp/algorithm/ranges/merge | Domain: Algorithms | Standards: C++20

Merges two sorted ranges [[first1, last1) and [first2, last2) into one sorted range beginning at result.

## Official Specification Summary (cppreference)

```cpp
// 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 `[[first1,` `last1)` and `[first2,` `last2)` 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 *algorithm function objects* (informally known as *niebloids*), that is:

- Explicit template argument lists cannot be specified when calling any of them.
- None of them are visible to argument-dependent lookup.
- When any of them are found by normal unqualified lookup as the name to the left of the function-call operator, argument-dependent lookup is inhibited.

### 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

```cpp
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

```cpp
#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:

```text
{ 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

- [`ranges::inplace_merge`](https://en.cppreference.com/w/cpp/algorithm/ranges/inplace_merge) (C++20): merges two ordered ranges in-place (algorithm function object)
- [`ranges::is_sorted`](https://en.cppreference.com/w/cpp/algorithm/ranges/is_sorted) (C++20): checks whether a range is sorted into ascending order (algorithm function object)
- [`ranges::set_union`](https://en.cppreference.com/w/cpp/algorithm/ranges/set_union) (C++20): computes the union of two sets (algorithm function object)
- [`ranges::sort`](https://en.cppreference.com/w/cpp/algorithm/ranges/sort) (C++20): sorts a range into ascending order (algorithm function object)
- [`ranges::stable_sort`](https://en.cppreference.com/w/cpp/algorithm/ranges/stable_sort) (C++20): sorts a range of elements while preserving order between equal elements (algorithm function object)
- [`merge`](https://en.cppreference.com/w/cpp/algorithm/merge): merges two sorted ranges (function template)

---
Attribution: content from https://en.cppreference.com/w/cpp/algorithm/ranges/merge (cppreference.com), licensed under CC-BY-SA 3.0 and GFDL. Modified: converted to markdown, study notes added. Offline snapshot of 9 February 2025.