merge() function in C++ Standard Template Library (STL)

Hello Folks!!!

Welcome to this tutorial. In this tutorial, you will be learning about the merge() function in C++ STL and how you can use it in your program. So let’s begin…

You can easily guess what this function is going to do. But let’s proceed step by step starting with the definition,

  • merge() function is a built-in function in C++ that accepts the “begin” and “end” iterators of the two containers to be merged and the “begin” iterator of a third container in which the merged result is going to be stored.

Input :

 A = {1, 2, 3, 4, 5}
 B = {6, 7, 8, 9, 10}

Output:

C = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
  • One thing to keep in mind is that, if the 1st container size is let say “N” and the 2nd container size is “M”. Then the destination container size must be equal to or greater than “M+N”.

(Note: In order to get a sorted merged container, the 2 containers that are to be merged should also contain the elements in a sorted manner.)

  • The general syntax for “merge()” function is
merge( container1_begin, container1_end, container2_begin, container2_end, container3_begin)

Here,

  1. container1_begin: Iterator to the beginning position of the first container.
  2. container1_endIterator to the final position of the first container.
  3. container2_begin: Iterator to the beginning position of the second container.
  4. container2_end: Iterator to the final position of the second container.
  5. container3_begin: Iterator to the beginning position of the resultant container.
  • This function returns an iterator to the end element of the merged container. Let’s understand the “merge()” function in detail with a code snippet.

 

How to use “merge()” function

// Using merge() function with arrays
#include <iostream>
#include <algorithm>

using namespace std;

int main(void)
{
    int arr_1[] = { 15 , 60 , 90 , 100 };
    int arr_2[] = { 5 , 10 , 30 , 40 , 50 };

    // Resultant container with size "M+N" i.e. "4 + 5 = 9"
    int arr_3[9];

    // Performing merge operation
    merge(arr_1, arr_1 + 4, arr_2, arr_2 + 5, arr_3);

    // Displaying contents of arr_3
    for (int i = 0 ; i<9; i++)
        cout << arr_3[i] << " ";

return 0;
}

Output for the above program is,

5 10 15 30 40 50 60 90 100
  • We can also use the merge() function with vectors. This function is very useful while performing the “MergeSort” operation where we need to merge and sort a given container.

So this is an overall concept about the “merge()” function in C++. I hope you have understood what is a merge() function and how to implement it in C++.

Thanks for reading this tutorial.

Comment down for any queries.

Leave a Reply

Your email address will not be published.