Given an STL vector, output only the duplicates in sorted order, e.g.,
INPUT : { 4, 4, 1, 2, 3, 2, 3 }
OUTPUT: { 2, 3, 4 }
The algorithm is
I miserably failed with my first attempt, assuming that std::unique
moves all the duplicates to the end of the range (it doesn't). Oops. Here's another attempt:
Here is an implementation of not_unique
. It removes any elements that appear only once in the sorted range and duplicates of any elements that appear more than once. The resulting range is therefore the unique list of elements that appear more than once.
The function has linear complexity and does a single pass over the range (std::unique
has linear complexity). It
must meet the requirements of a forward iterator. The end of the resulting range is returned.
template
It not_unique(It first, It last)
{
if (first == last) { return last; }
It new_last = first;
for (It current = first, next = ++first; next != last; ++current, ++next)
{
if (*current == *next)
{
if (current == new_last)
{
++new_last;
}
else
{
*new_last++ = *current;
while (next != last && *current == *next)
{
++current;
++next;
}
if (next == last)
return new_last;
}
}
}
return new_last;
}