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
This fixes the bugs in James McNellis's original version. I also provide in-place and out-of-place versions.
// In-place version. Uses less memory and works for more container
// types but is slower.
template
It not_unique_inplace(It first, It last)
{
if (first == last)
return last;
It new_last = first;
for (It current = first, next = first + 1; next != last; ++current, ++next)
{
if (*current == *next &&
(new_last == first || *current != *(new_last-1)))
*new_last++ = *current;
}
return new_last;
}
// Out-of-place version. Fastest.
template
void not_unique(It first, It last, Container pout)
{
if (first == last || !pout)
return;
for (It current = first, next = first + 1; next != last; ++current, ++next)
{
if (*current == *next &&
(pout->empty() || *current != pout->back()))
pout->push_back(*current);
}
}