给定STL向量,仅按排序顺序输出重复项,例如,
INPUT : { 4, 4, 1, 2, 3, 2, 3 }
OUTPUT: { 2, 3, 4 }
Run Code Online (Sandbox Code Playgroud)
该算法很简单,但目标是使其与std :: unique()一样高效.我天真的实现就地修改了容器:
我天真的实施:
void not_unique(vector<int>* pv)
{
if (!pv)
return;
// Sort (in-place) so we can find duplicates in linear time
sort(pv->begin(), pv->end());
vector<int>::iterator it_start = pv->begin();
while (it_start != pv->end())
{
size_t nKeep = 0;
// Find the next different element
vector<int>::iterator it_stop = it_start + 1;
while (it_stop != pv->end() && *it_start == *it_stop)
{
nKeep = 1; // …Run Code Online (Sandbox Code Playgroud)