The Wayback Machine - https://web.archive.org/web/20240730031726/https://www.geeksforgeeks.org/merge-in-cpp-stl/
Open In App

merge() in C++ STL

Last Updated : 14 Sep, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

C++ offers in its STL library a merge() which is quite useful to merge sort two containers into a single container. It is defined in header “algorithm“. It is implemented in two ways. Syntax 1 : Using operator “<” 

Template :
template 
  outiter merge (initer1 beg1, initer1 end1,
                        initer2 beg2, initer2 end2,
                        outiter res)

Parameters :
beg1 :  Input iterator to initial position of first sequence.
end1 :  Input iterator to final position of first sequence.

beg2 :  Input iterator to initial position of second sequence.
end2 :  Input iterator to final position of second sequence.

res : Output Iterator to initial position of resultant container.
Return value : 
Iterator to last element of the resulting container.

 

CPP




// C++ code to demonstrate the working of
// merge() implementation 1
 
#include <bits/stdc++.h>
using namespace std;
 
int main()
{
    // initializing 1st container
    vector<int> arr1 = { 1, 4, 6, 3, 2 };
 
    // initializing 2nd container
    vector<int> arr2 = { 6, 2, 5, 7, 1 };
 
    // declaring resultant container
    vector<int> arr3(10);
 
    // sorting initial containers
    sort(arr1.begin(), arr1.end());
    sort(arr2.begin(), arr2.end());
 
    // using merge() to merge the initial containers
    merge(arr1.begin(), arr1.end(), arr2.begin(), arr2.end(), arr3.begin());
 
    // printing the resultant merged container
    cout << "The container after merging initial containers is : ";
 
    for (int i = 0; i < arr3.size(); i++)
        cout << arr3[i] << " ";
    return 0;
}


Output:

The container after merging initial containers is : 1 1 2 2 3 4 5 6 6 7 

Syntax 2 : Using comparator function 

Template :
template 
  outiter merge (initer1 beg1, initer1 end1,
                        initer2 beg2, initer2 end2,
                        outiter res, Compare comp)

Parameters :
beg1 :  Input iterator to initial position of first sequence.
end1 :  Input iterator to final position of first sequence.

beg2 :  Input iterator to initial position of second sequence.
end2 :  Input iterator to final position of second sequence.

res : Output Iterator to initial position of resultant container.
comp : The comparator function that returns a boolean
true/false of the each elements compared. This function 
accepts two arguments. This can be function pointer or 
function object and cannot change values.
Return value : 
Iterator to last element of the resulting container.

 

CPP




// C++ code to demonstrate the working of
// merge() implementation 2
 
#include <bits/stdc++.h>
using namespace std;
 
// comparator function to reverse merge sort
struct greaters {
    bool operator()(const long& a, const long& b) const
    {
        return a > b;
    }
};
 
int main()
{
    // initializing 1st container
    vector<int> arr1 = { 1, 4, 6, 3, 2 };
 
    // initializing 2nd container
    vector<int> arr2 = { 6, 2, 5, 7, 1 };
 
    // declaring resultant container
    vector<int> arr3(10);
 
    // sorting initial containers
    // in descending order
    sort(arr1.rbegin(), arr1.rend());
    sort(arr2.rbegin(), arr2.rend());
 
    // using merge() to merge the initial containers
    // returns descended merged container
    merge(arr1.begin(), arr1.end(), arr2.begin(), arr2.end(), arr3.begin(), greaters());
 
    // printing the resultant merged container
    cout << "The container after reverse merging initial containers is : ";
 
    for (int i = 0; i < arr3.size(); i++)
        cout << arr3[i] << " ";
    return 0;
}


Output :

The container after reverse merging initial containers is : 7 6 6 5 4 3 2 2 1 1 

Possible application : The merge function can be used to make a single stack of two stacks available in sorted order. These can be stack of books or notes. Let us discuss a simple example that merge orders two stack of notes in ascending order into one on basis of its value. 

CPP




// C++ code to demonstrate the application of
// merge() stacking notes
 
#include <bits/stdc++.h>
using namespace std;
 
int main()
{
    // initializing 1st container
    // containing denominations
    vector<int> stack1 = { 50, 20, 10, 100, 2000 };
 
    // initializing 2nd container
    // containing denominations
    vector<int> stack2 = { 500, 2000, 10, 100, 50 };
 
    // declaring resultant stack
    vector<int> stack3(10);
 
    cout << "The original 1st stack : ";
    for (int i = 0; i < 5; i++)
        cout << stack1[i] << " ";
 
    cout << endl;
 
    cout << "The original 2nd stack : ";
    for (int i = 0; i < 5; i++)
        cout << stack2[i] << " ";
 
    cout << endl;
 
    // sorting initial stacks of notes
    // in descending order
    sort(stack1.begin(), stack1.end());
    sort(stack2.begin(), stack2.end());
 
    // using merge() to merge the initial stacks
    // of notes
    merge(stack1.begin(), stack1.end(), stack2.begin(), stack2.end(), stack3.begin());
 
    // printing the resultant stack
    cout << "The resultant stack of notes is : ";
 
    for (int i = 0; i < stack3.size(); i++)
        cout << stack3[i] << " ";
    return 0;
}


Output :

The original 1st stack : 50 20 10 100 2000 
The original 2nd stack : 500 2000 10 100 50 
The resultant stack of notes is : 10 10 20 50 50 100 100 500 2000 2000 



Similar Reads

Merge operations using STL in C++ | merge(), includes(), set_union(), set_intersection(), set_difference(), ., inplace_merge,
Some of the merge operation classes are provided in C++ STL under the header file "algorithm", which facilitates several merge operations in a easy manner. Some of them are mentioned below. merge(beg1, end1, beg2, end2, beg3) :- This function merges two sorted containers and stores in new container in sorted order (merge sort). It takes 5 arguments
7 min read
forward_list merge() in C++ STL
forward_list::merge() is an inbuilt function in C++ STL which merges two sorted forward_lists into one. The merge() function can be used in two ways: Merge two forward lists that are sorted in ascending order into one. Merge two forward lists into one using a comparison function. Syntax: forwardlist_name1.merge(forward_list&amp; forwardlist_name2)
2 min read
list merge() function in C++ STL
The list::merge() is an inbuilt function in C++ STL which merges two sorted lists into one. The lists should be sorted in ascending order. If no comparator is passed in parameter, then it merges two sorted lists into a single sorted list. If a comparator is passed in the parameter, then it merges the list accordingly doing internal comparisons. Syn
2 min read
Quickly merging two sorted arrays using std::merge() in C++ STL
C++ program to merge two sorted arrays of length 'n' and 'm' respectively in sorted order. Examples: Input: A[] = {3, 6, 9} B[] = {2, 7, 11} Output: C[] = {2, 3, 6, 7, 9, 11} Input: A[] = {1, 1, 3, 6, 9} B[] = {1, 2, 7, 11, 11} Output: C[] = {1, 1, 1, 2, 3, 6, 7, 9, 11, 11} We have discussed other approaches in below posts Merge two sorted arrays w
2 min read
Merge two sorted arrays in Python using heapq
Given two sorted arrays, the task is to merge them in a sorted manner. Examples: Input : arr1 = [1, 3, 4, 5] arr2 = [2, 4, 6, 8] Output : arr3 = [1, 2, 3, 4, 4, 5, 6, 8] Input : arr1 = [5, 8, 9] arr2 = [4, 7, 8] Output : arr3 = [4, 5, 7, 8, 8, 9] This problem has existing solution please refer Merge two sorted arrays link. We will solve this proble
2 min read
Sorted merge in one array
Given two sorted arrays, A and B, where A has a large enough buffer at the end to hold B. Merge B into A in sorted order. Examples: Input : a[] = {10, 12, 13, 14, 18, NA, NA, NA, NA, NA} b[] = {16, 17, 19, 20, 22};; Output : a[] = {10, 12, 13, 14, 16, 17, 18, 19, 20, 22} One way is to merge the two arrays by inserting the smaller elements in front
7 min read
Number of ways to merge two arrays such retaining order
Given two array of size n and m. The task is to find the number of ways we can merge the given arrays into one array such that order of elements of each array doesn't change. Examples: Input : n = 2, m = 2 Output : 6 Let first array of size n = 2 be [1, 2] and second array of size m = 2 be [3, 4]. So, possible merged array of n + m elements can be:
7 min read
In-Place Merge Sort
Implement Merge Sort i.e. standard implementation keeping the sorting algorithm as in-place. In-place means it does not occupy extra memory for merge operation as in the standard case. Examples: Input: arr[] = {2, 3, 4, 1} Output: 1 2 3 4 Input: arr[] = {56, 2, 45} Output: 2 45 56 Approach 1: Maintain two pointers that point to the start of the seg
15+ min read
Merge transactions in bank sheets in the order of their occurrence such that their sum remains positive
Given an array arr[][] consisting of N lists representing N transactions, the task is to merge the given lists of transactions in the order of their occurrences, such that at any point of time, the sum of already performed transactions is non-negative. If found to negative, then print "-1". Otherwise, print the merged list of transactions. Examples
7 min read
Python3 Program for Merge 3 Sorted Arrays
Given 3 arrays (A, B, C) which are sorted in ascending order, we are required to merge them together in ascending order and output the array D. Examples: Input : A = [1, 2, 3, 4, 5] B = [2, 3, 4] C = [4, 5, 6, 7] Output : D = [1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 6, 7] Input : A = [1, 2, 3, 5] B = [6, 7, 8, 9 ] C = [10, 11, 12] Output: D = [1, 2, 3, 5, 6,
8 min read
Practice Tags :
three90RightbarBannerImg