unique_copy |
Copy a sequence, collapsing consecutive values.
Copy the sequence [
first ... last ) to a sequence starting at result
, replacing all consecutive occurrences of a value by a single instance of that
value. Return an iterator positioned immediately after the last element of the
new sequence. The first version uses operator== to
determine equality, whereas the second version uses the binary function binary_pred
.
#include <algorithm>
template< class InputIterator, class OutputIterator >
OutputIterator unique_copy
(
InputIterator first,
InputIterator last,
OutputIterator result
);
template< class InputIterator, class OutputIterator,
class BinaryPredicate >
OutputIterator unique_copy
(
InputIterator first,
InputIterator last,
OutputIterator result,
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 result[ 8 ] = { 0, 0, 0, 0, 0, 0, 0, 0 };
void
main()
{
unique_copy( numbers, numbers + 8, result );
for ( int i = 0; i < 8; ++i )
cout << result[ i ] << ` `;
cout << "\n";
}
0 1 2 3 4 0 0 0
#include <iostream>
#include <string.h>
#include <algorithm>
const 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;
}
void
main()
{
const unsigned count = sizeof( labels ) / sizeof( labels[ 0 ] );
ostream_iterator< const char* > iter( cout );
copy( labels, labels + count, iter );
cout << "\n";
const char* u_copy[ count ];
fill (u_copy, u_copy + count, "" );
unique_copy( labels, labels + count, u_copy, str_equal );
copy( labels, labels + count, iter );
cout << "\n";
copy( u_copy, u_copy + count, iter );
cout << "\n";
}
QQWWEERRTTYY
QQWWEERRTTYY
QWERTY
Copyright©1994-2026 Recursion Software LLC
All Rights Reserved - For use by licensed users only.