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
You can even use mismatch, for extra points!
Btw: nice exercise.
template
/** Moves duplicates to front, returning end of duplicates range.
* Use a sorted range as input. */
TIter Duplicates(TIter begin, TIter end) {
TIter dup = begin;
for (TIter it = begin; it != end; ++it) {
TIter next = it;
++next;
TIter const miss = std::mismatch(next, end, it).second;
if (miss != it) {
*dup++ = *miss;
it = miss;
}
}
return dup;
}