Related Tags

communitycreator
c++

# How to use the inplace_merge() function in C++

Vinisha Maheshwari

The inplace_merge() function is present in the <algorithm> library. It is used to merge two consecutive sorted ranges in a sorted range.

### Syntax

void inplace_merge(Begin1, Begin2, Last, Pred);



### Parameters

The inplace_merge() function takes the following parameters:

• Begin1: A bidirectional iterator pointing to the initial position of the first sorted range.

• Begin2: A bidirectional iterator pointing to the initial position of the second sorted range which matches the past end position of the first range.

• Last: A bidirectional iterator pointing to the past end position of the second sorted range.

• Pred: A user-defined function that returns true if the two arguments passed are in order (follows strict weak ordering).

### Return

The function does not return anything.

## Example

Let us take two different ranges.

Range1 = $\{1,2,4,5\}$

Range2 = $\{10,9,8,7,3\}$

The merged sorted range = $\{1,2,3,4,5,7,8,9,10\}$

### Code

Let’s take a look at the following code snippet.

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main ()
{
int f[] = {5,9,15,27,3};
int s[] = {23,21,90,34,40};
vector<int> v(10);
vector<int>::iterator i;

sort (f,f+5);
sort (s,s+5);

i=copy (f, f+5, v.begin());
copy (s,s+5,i);

inplace_merge (v.begin(),v.begin()+5,v.end());

cout << "The merged sorted vector is:";
for (i=v.begin(); i!=v.end(); i++)
cout << ' ' << *i;
return 0;
}

Using inplace_merge() function in C++

### Explanation

• In lines 1 to 3, we import the required libraries.
• In line 5, we make a main function.
• In lines 7 and 8, we initialize two arrays.
• In line 9, we declare a vector.
• In line 10, we declare an iterator to a vector.
• In lines 12 and 13, we sort both the arrays.
• In line 15, we assign the copy of the first array to the vector in the iterator.
• In line 16, we assign the copy of the first array to the vector in the iterator.
• In line 18, we use the inplace_merge() function to merge the two sorted ranges.
• In line 20, we display the message regarding the merged sorted vector.
• In lines 21 and 22, we use a loop to access the merge sorted vector’s elements and display them.

RELATED TAGS

communitycreator
c++

CONTRIBUTOR

Vinisha Maheshwari
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time 