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 !