尝试改进算法以使其更通用

Trying to improve algorithm to be more generic

我提出了以下算法来删除向量中的连续重复项,但我正在寻找一种方法来改进它并能够将其与其他顺序容器一起使用。

我四处寻找通用的父容器类型,但到目前为止我什么都想不出来。

有什么想法吗?

谢谢!

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

C++ 标准库中已有通用算法 std::unique (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.

这是一个演示程序

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

它的输出是

1 3 2

考虑到数组没有像 erase 这样的成员函数。因此,您不能为每个包含 erase.

调用的顺序容器编写通用函数

您可以为容器类型创建模板,例如:

template <class Cont>
void erase_adjacent_duplicate(Cont& cont)
{
     cont.erase(std::unique(std::begin(cont), std::end(cont)), std::end(cont));
}

不要寻找共同的父容器,而是使用迭代器作为输入。然后你可以编写你的算法,例如它对所有 InputIterators 都有效。参见 http://en.cppreference.com/w/cpp/iterator