unique |
Collapse all consecutive values in a sequence.
Replace all consecutive matching
occurrences of a value in the range [ first ...
last ) by a single instance of that value. Return an iterator positioned
immediately after the last element of the new sequence. The size of the
container is not altered. If n elements are removed,
the last n elements of the sequence [
first ... last ) have undefined values. The first
version uses operator== to match values, whereas
the second version uses the binary function binary_pred
.
#include <algorithm>
template< class ForwardIterator >
ForwardIterator unique
(
ForwardIterator first,
ForwardIterator last
);
template< class ForwardIterator, class BinaryPredicate >
ForwardIterator unique
(
ForwardIterator first,
ForwardIterator last,
BinaryPredicate binary_pred
);
Time complexity is linear, as (
last - first )
operations are performed. Space complexity is constant.
#include <iostream>
#include <algorithm>
int numbers[ 8 ] = { 0, 1, 1, 2, 2, 2, 3, 4 };
int main()
{
unique( numbers, numbers + 8 );
for ( int i = 0; i < 8; i ++ )
cout << numbers[ i ] << ` `;
cout << "\n";
}
0 1 2 3 4 2 3 4
#include <iostream>
#include <string.h>
#include <algorithm>
char* labels[] = { "Q","Q","W","W","E","E","R","T","T","Y","Y" };
bool
str_equal( const char* a_, const char* b_ )
{
return ::strcmp( a_, b_ ) == 0 ? 1 : 0;
}
int main()
{
const unsigned count = sizeof( labels ) / sizeof( labels[ 0 ] );
ostream_iterator< char* > iter( cout );
copy( labels, labels + count, iter );
cout << "\n";
unique( labels, labels + count, str_equal );
copy( labels, labels + count, iter );
cout << "\n";
}
QQWWERRTTYY
QWERTYRTTYY
Copyright©1994-2026 Recursion Software LLC
All Rights Reserved - For use by licensed users only.