algorithm - STL C++

merge()

Declaration

template <class InputIter1, class InputIter2, class OutputIter>
OutputIter merge(
	InputIter1 xFirst1,
	InputIter1 xLast1,
	InputIter2 xFirst2,
	InputIter2 xLast2,
	OutputIter xOutput
);

Description

This function merges the ordered range of entries starting at "xFirst1" up to the one before "xLast1" with the ordered range of entries starting at "xFirst2" up to the one before "xLast2." The result is that the entries in these two ranges is now ordered at the location of the iterator "xOutput." In the overloaded version, the comparison function "xComp" is used to define the ordering.

Header Include

#include <algorithm>

Overloads

template <class InputIter1, class InputIter2, class OutputIter, class BinaryPred>
OutputIter merge(
	InputIter1 xFirst1,
	InputIter1 xLast1,
	InputIter2 xFirst2,
	InputIter2 xLast2,
	OutputIter xOutput,
	BinaryPred xComp
);

Example

#include <iostream>
#include <vector>
#include <algorithm>

int main()
{
	using namespace std;

	// Create two vector instances
	vector<int> qV1;
	for (int i = 0; i < 10; i += 2) {
		qV1.push_back(i);
	}
	vector<int> qV2;
	for (int i = -2; i < 9; i += 3) {
		qV2.push_back(i);
	}

	vector<int>::iterator qIter;
	cout << "Vector1: ";
	for (qIter = qV1.begin(); qIter != qV1.end(); ++qIter) {
		cout << *qIter << "  ";
	}
	cout << endl;
	cout << "Vector2: ";
	for (qIter = qV2.begin(); qIter != qV2.end(); ++qIter) {
		cout << *qIter << "  ";
	}
	cout << endl;

	vector<int> qResult(9);
	// Merge the five entries with four.
	merge(qV1.begin(), qV1.end(), qV2.begin(), qV2.end(), qResult.begin());

	cout << "Merged Vector: ";
	for (qIter = qResult.begin(); qIter != qResult.end(); ++qIter) {
		cout << *qIter << "  ";
	}
	cout << endl;

	// Keep the window open
	cin.get();
	return 0;
}

Output

merge() Output
 

© 2007–2024 XoaX.net LLC. All rights reserved.