Search code examples
c++algorithmtemplatescontainerssequential

Trying to improve algorithm to be more generic


I came up with the following algo to remove consecutive duplicates in a vector, but I am looking for a way to improve it and to be able to use it with other sequential containers.

I've looked around for a common parent container type, but I can't figure anything out so far.

Any ideas?

Thanks!

template <class T>
void erase_adjacent_duplicate (std::vector<T>& v)
{
    std::vector<T>::iterator it = v.begin();

    while (it != v.end()) 
    {
        if(std::adjacent_find(it, v.end()) == v.end())
        {
            it = v.end();
        }
        else
        {
            it = std::adjacent_find(it, v.end()) - 1;
            v.erase(it + 1);
        }
    }
}

Solution

  • There is already general algorithm std::unique in the C++ standard library that (The C++ Standard )

    eliminates all but the first element from every consecutive group of equivalent elements referred to by the iterator i in the range [first + 1,last) for which the following conditions hold: *(i - 1) == i or pred((i - 1), *i) != false.

    Here is a demonstrative program

    #include <iostream>
    #include <vector>
    #include <algorithm>
    
    int main() 
    {
        std::vector<int> v = { 1, 1, 3, 3, 3, 2, 2 };
    
        v.erase(std::unique(v.begin(), v.end()), v.end());
    
        for (int x : v) std::cout << x << ' ';
        std::cout << std::endl;
    
        return 0;
    }
    

    Its output is

    1 3 2
    

    Take into account that arrays do not have member functions like erase. So you can not write a general function for each sequential container that includes a call of erase.