How to make elements of vector unique? (remove non adjacent duplicates)

后端 未结 11 1043
醉梦人生
醉梦人生 2020-11-29 05:01

I have a vector containing few non-adjacent duplicates.

As a simple example, consider:

2 1 6 1 4 6 2 1 1

I am trying to make this

11条回答
  •  余生分开走
    2020-11-29 05:33

    Without using a temporary set it's possible to do this with (possibly) some loss of performance:

    template
    Iterator Unique(Iterator first, Iterator last)
    {
        while (first != last)
        {
            Iterator next(first);
            last = std::remove(++next, last, *first);
            first = next;
        }
    
        return last;
    }
    

    used as in:

    vec.erase( Unique( vec.begin(), vec.end() ), vec.end() );
    

    For smaller data sets, the implementation simplicity and lack of extra allocation required may offset the theoretical higher complexity of using an additional set. Measurement with a representative input is the only way to be sure, though.

提交回复
热议问题