Javatpoint Logo
Javatpoint Logo

C++ Algorithm inplace_merge()

C++ Algorithm inplace_merge() function is used to merge two consecutive sorted ranges [first, last) and [middle, last) into one sorted range [first, last).

Elements are compared using operator < for the first version or using the given binary comparison function comp for the second version.

Syntax

Parameter

first: A bidirectional iterator pointing to the first element in the first of two consecutive sorted ranges to be merged and sorted into single range.

last: A bidirectional iterator pointing to the past last element in the second of two consecutive sorted ranges to be merged and sorted into single range.

middle: A bidirectional iterator pointing to the position of the first element in the second of two consecutive sorted ranges to be merged and sorted into a single range.

comp: A user-defined binary predicate function that accepts two arguments and returns true if the two arguments are in order otherwise false. It follows the strict weak ordering to order the elements.

Return value

None

Complexity

If enough extra memory is available, then the complexity is linear in the distance between first and last: performs N-1 comparisons and up to twice that many elements moves.

Otherwise, complexity is linearithmic: performs up to N*log(N) element comparisons where N = last -first and up to that many elements swaps.

Data races

The object in the range [first, last) are modified.

Exceptions

This function throws an exception if any of element comparison, the element swaps (or moves) or an operation on iterator throws an exception.

Note: The invalid parameters cause an undefined behavior.

Example 1

Let's see the simple example to demonstrate the use of inplace_merge():

Output:

Vector v1 :  5 10 15 20 25
Vector v2 :  10 20 30 40 50
Vector v3 :  5 10 10 15 20 20 25 30 40 50

Example 2

Let's see another simple example:

Output:

The resulting vector contains: 5 10 10 15 20 20 25 30 40 50

Example 3

Let's see another simple example demonstrate the use of inplace_merge() using operator<:

Output:

1
2
3
4
5

Example 4

Let's see a simple example to demonstrate the use of inplace_merge() using comparison function:

Output:

5
4
3
2
1

Example 5

Let's see another simple example:

Output:

-9 0 1 2 3 4 7 9 10

Next TopicC++ Algorithm




Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


B.Tech / MCA