Home » C++ algorithm merge() function

C++ algorithm merge() function

by Online Tutorials Library

C++ Algorithm merge()

C++ Algorithm merge() function is used to merge two sorted ranges [first1, last1) and [first2, last2) into one sorted range beginning at result.

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

Syntax

Parameter

first1: An input iterator pointing to the first element in the first sorted source sequence to be merged.

last: A input iterator pointing to the past last element in the first sorted source sequence to be merged.

first2: An input iterator pointing to the first element in the second sorted source sequence to be merged.

last2: An input iterator pointing to the past last element in the second sorted source sequence to be merged.

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

val: A value of the upper bound to compare the elements in the range.

result: An output iterator pointing to the first element in the destination range where the two source ranges are to be combined into a single sorted range.

Return value

It returns an iterator pointing to the past last element in the resulting sequence.

Complexity

Complexity is linear: performs at most (last1-first1) + (last2 – first2) – compares and assigns all elements.

Data races

The object in the range [first1, last1) and [first2, last2) are accessed.

The object in the range between result and the returned value are altered.

Exceptions

This function throws an exception if either an element comparisons or an operation on iterator throws an exception.

Please note that invalid parameters cause an undefined behavior.

Example 1

Let’s see the simple example to demonstrate the use of merge():

Output:

Vector v1 :  1 2 4 5 6  Vector v2 :  10 20 30 40 50  Vector v3 :  1 2 4 5 6 10 20 30 40 50  

Example 2

Let’s see another simple example to implement merge() function using operator <

Output:

The container after merging initial containers is: 1 2 3 4 6 10 20 50 60 70  

Example 3

Let’s see another simple example to demonstrate merge() using comparison function

Output:

The container after reverse merging initial containers is : 70 60 50 20 10 6 4 3 2 1  

Example 4

Let’s see another simple exampl

Output:

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

Next TopicC++ Algorithm

You may also like