C++ std::merge
The algorithm std::merge
function in C++ is used to merge two sorted ranges into a single sorted range. It operates based on the sorting order of the input ranges. The result is written to a destination range starting from the specified output iterator.
Syntax of std::merge
template <class InputIterator1, class InputIterator2, class OutputIterator>
OutputIterator merge(InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, InputIterator2 last2,
OutputIterator result);
template <class InputIterator1, class InputIterator2, class OutputIterator, class Compare>
OutputIterator merge(InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, InputIterator2 last2,
OutputIterator result, Compare comp);
Parameters of std::merge
Parameter | Description |
---|---|
first1, last1 | Input iterators defining the first sorted range to merge. |
first2, last2 | Input iterators defining the second sorted range to merge. |
result | Output iterator to the beginning of the destination range where the merged elements are stored. |
comp (optional) | A binary comparison function that defines the order of elements. Defaults to < . |
Return Value of std::merge
Returns an iterator to the element in the destination range corresponding to the end of the merged range.
Examples for std::merge
Example 1: Basic Usage of std::merge
This example demonstrates merging two sorted arrays into a single sorted array.
Steps:
- Create two sorted input vectors,
vec1
andvec2
, with elements{1, 3, 5, 7}
and{2, 4, 6, 8}
, respectively. - Initialize a third vector,
result
, with a size equal to the sum of the sizes ofvec1
andvec2
. This vector will hold the merged elements. - Call the
std::merge
function to merge the two sorted input vectors into theresult
vector:- Provide the range of
vec1
usingvec1.begin()
andvec1.end()
. - Provide the range of
vec2
usingvec2.begin()
andvec2.end()
. - Specify the destination range starting at
result.begin()
.
- Provide the range of
- Iterate over the
result
vector using a range-basedfor
loop and print each element to the console.
Program:
#include <iostream>
#include <algorithm>
#include <vector>
int main() {
std::vector<int> vec1 = {1, 3, 5, 7};
std::vector<int> vec2 = {2, 4, 6, 8};
std::vector<int> result(vec1.size() + vec2.size());
std::merge(vec1.begin(), vec1.end(), vec2.begin(), vec2.end(), result.begin());
std::cout << "Merged array: ";
for (int n : result) {
std::cout << n << " ";
}
std::cout << std::endl;
return 0;
}
Output:
Merged array: 1 2 3 4 5 6 7 8
Example 2: Using a Custom Comparison Function for std::merge
This example demonstrates merging two sorted ranges using a custom comparison function:
Steps:
- Define a custom comparison function named
descending
that takes two integers as arguments and returnstrue
if the first integer is greater than the second. This will enable sorting in descending order. - Create two sorted input vectors,
vec1
with elements{7, 5, 3, 1}
andvec2
with elements{8, 6, 4, 2}
. These vectors are already sorted in descending order. - Initialize a third vector,
result
, with a size equal to the sum of the sizes ofvec1
andvec2
. This vector will hold the merged elements. - Call the
std::merge
function to merge the two sorted input vectors into theresult
vector in descending order:- Provide the range of
vec1
usingvec1.begin()
andvec1.end()
. - Provide the range of
vec2
usingvec2.begin()
andvec2.end()
. - Specify the destination range starting at
result.begin()
. - Pass the custom comparison function
descending
to ensure the merge is done in descending order.
- Provide the range of
- Iterate over the
result
vector using a range-basedfor
loop and print each element to the console.
Program
#include <iostream>
#include <algorithm>
#include <vector>
bool descending(int a, int b) {
return a > b;
}
int main() {
std::vector<int> vec1 = {7, 5, 3, 1};
std::vector<int> vec2 = {8, 6, 4, 2};
std::vector<int> result(vec1.size() + vec2.size());
std::merge(vec1.begin(), vec1.end(), vec2.begin(), vec2.end(), result.begin(), descending);
std::cout << "Merged array in descending order: ";
for (int n : result) {
std::cout << n << " ";
}
std::cout << std::endl;
return 0;
}
Output:
Merged array in descending order: 8 7 6 5 4 3 2 1
Exception Handling in std::merge
The std::merge
function itself does not throw exceptions. However, the comparison function passed as an argument may throw exceptions, which can be caught and handled appropriately.
Example 1: Exception in Custom Comparison Function
This example demonstrates how exceptions in a custom comparison function are handled:
Algorithm Steps:
- Define a custom comparison function named
faulty_compare
that throws astd::runtime_error
if either of the integers being compared is5
. Otherwise, it compares the integers in ascending order. - Initialize two sorted input vectors:
vec1
with elements{1, 3, 5}
.vec2
with elements{2, 4, 6}
.
- Create a third vector,
result
, with a size equal to the combined size ofvec1
andvec2
. This vector will store the merged output. - Wrap the merge operation in a
try
block to handle potential exceptions from thefaulty_compare
function. - Call the
std::merge
function with the following arguments:- The range of
vec1
defined byvec1.begin()
andvec1.end()
. - The range of
vec2
defined byvec2.begin()
andvec2.end()
. - The destination range starting at
result.begin()
. - The custom comparison function
faulty_compare
.
- The range of
- If
faulty_compare
encounters the value5
, it throws astd::runtime_error
, interrupting the merge operation. - In the
catch
block, capture the exception and print an error message to the console usingstd::cerr
, indicating the reason for the failure.
Program
#include <iostream>
#include <algorithm>
#include <vector>
#include <stdexcept>
bool faulty_compare(int a, int b) {
if (a == 5 || b == 5) {
throw std::runtime_error("Comparison involving 5 is not allowed.");
}
return a < b;
}
int main() {
std::vector<int> vec1 = {1, 3, 5};
std::vector<int> vec2 = {2, 4, 6};
std::vector<int> result(vec1.size() + vec2.size());
try {
std::merge(vec1.begin(), vec1.end(), vec2.begin(), vec2.end(), result.begin(), faulty_compare);
} catch (const std::exception& e) {
std::cerr << "Exception caught: " << e.what() << std::endl;
}
return 0;
}
Output:
Exception caught: Comparison involving 5 is not allowed.