Standard C++ Library Class Reference
OutputIterator result, Compare comp);
Description
The merge algorithm merges two sorted seqeunces, specified by [first1, last1) and [first2, last2),
into the sequence specified by [result, result + (last1 - first1) + (last2 - first2)). The first version
of the merge algorithm uses the less than operator (<) to compare elements in the two
sequences. The second version uses the comparision function provided by the function call. If a
comparison function is provided, merge assumes that both sequences were sorted using that
comparison function.
The merge is stable. This means that if the two original sequences contain equivalent elements,
the elements from the first sequence will always precede the matching elements from the
second in the resulting sequence. The size of the result of a merge is equal to the sum of the
sizes of the two argument sequences. merge returns an iterator that points to the end of the
resulting sequence, i.e., result + (last1 - first1) + (last2 -first2). The result of merge is undefined
if the resulting range overlaps with either of the original ranges.
merge assumes that there are at least (last1 - first1) + (last2 - first2) elements following result,
unless result has been adapted by an insert iterator.
Complexity
For merge at most (last - first1) + (last2 - first2) - 1 comparisons are performed.
Example
//
// merge.cpp
//
#include <algorithm>
#include <vector>
#include <iostream.h>
int main()
{
int d1[4] = {1,2,3,4};
int d2[8] = {11,13,15,17,12,14,16,18};
// Set up two vectors
vector<int> v1(d1,d1 + 4), v2(d1,d1 + 4);
// Set up four destination vectors
vector<int> v3(d2,d2 + 8),v4(d2,d2 + 8),
v5(d2,d2 + 8),v6(d2,d2 + 8);
// Set up one empty vector
vector<int> v7;
// Merge v1 with v2