DEV Community

dinhluanbmt
dinhluanbmt

Posted on

C++, remove all duplicated, multiple value in sorted vector

Just a quick way to remove all multiple, duplicated values in a sorted array

template <class T>
void removeAllDuplicates(vector<T>& vec) {
    size_t i;
    size_t pos = 0;
    for (i = 1; i < vec.size(); i++) {
        if (vec[i] != vec[pos]) {
            pos++;
            vec[pos] = vec[i];
        }
    }
    vec.erase(vec.begin() + pos + 1, vec.end());
}
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
pauljlucas profile image
Paul J. Lucas

Simpler:

vec.erase( std::unique( vec.begin(), vec.end() ), vec.end() );
Enter fullscreen mode Exit fullscreen mode
Collapse
 
dinhluanbmt profile image
dinhluanbmt

nice !

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay