algorithm - STL C++

unique()

Declaration

template <class FwdIter>
FwdIter unique(
	FwdIter xFirst,
	FwdIter xLast
);

Description

This function removes all of the duplicate entries in the range from "xFirst" up to the entry before "xLast" and returns an iterator to the new end of the entries that has the duplicates removed. The overloaded version uses the function "xComp" to test equality.

Header Include

#include <algorithm>

Overloads

template <class FwdIter, class Pred>
FwdIter unique(
	FwdIter xFirst,
	FwdIter xLast,
	Pred 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>::iterator qIter;
	// Output the vector
	cout << "Vector: ";
	for (qIter = qV.begin(); qIter != qV.end(); ++qIter) {
		cout << *qIter;
	}
	cout << endl;

	// Remove any adjacent duplicates
	vector<char>::iterator qNewEndIter;
	qNewEndIter = unique(qV.begin(), qV.end());

	// Output the vector after the call to unique
	cout << "Vector: ";
	for (qIter = qV.begin(); qIter != qNewEndIter; ++qIter) {
		cout << *qIter;
	}
	cout << endl;

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

Output

unique() Output
 

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