How to keep only duplicates efficiently?

后端 未结 10 742
闹比i
闹比i 2021-01-04 06:14

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

10条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-04 06:58

    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);
        }
    }
    

提交回复
热议问题