algorithm - STL C++

unique_copy()

Declaration

template <class InIter, class OutIter>
OutIter unique_copy(
	InIter xFirst,
	InIter xLast,
	OutIter xDest
);

Description

This function copies the entries, not adjacent duplicate entries, in the range from "xFirst" to the one before "xLast" to the location specified by "xDest," writing over the entries. The function returns a pointer to the end of the newly copied range. The overloaded version uses "xComp" as a comparison function instead of "==."

Header Include

#include <algorithm>

Overloads

template <class InIter, class OutIter, class BinaryPred>
OutIter unique_copy(
	InIter xFirst,
	InIter xLast,
	OutIter xDest,
	BinaryPred xComp
);

Example

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

int main()
{
	using namespace std;

	// Create a vector instance
	vector<char> qV;
	qV.push_back('X');
	qV.push_back('o');
	qV.push_back('a');
	qV.push_back('X');
	qV.push_back('X');
	qV.push_back('X');
	qV.push_back('.');
	qV.push_back('n');
	qV.push_back('e');
	qV.push_back('t');

	vector<char> qCopy(10);

	vector<char>::iterator qIter;
	// Output the original vector
	cout << "Original Vector: ";
	for (qIter = qV.begin(); qIter != qV.end(); ++qIter) {
		cout << *qIter;
	}
	cout << endl;

	// Copy and remove any adjacent duplicates
	vector<char>::iterator qNewEndIter;
	qNewEndIter = unique_copy(qV.begin(), qV.end(), qCopy.begin());

	// Output the copied vector
	cout << "Copied Vector: ";
	for (qIter = qCopy.begin(); qIter != qNewEndIter; ++qIter) {
		cout << *qIter;
	}
	cout << endl;

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

Output

unique_copy() Output
 

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