代码之家  ›  专栏  ›  技术社区  ›  aJ.

如何使向量元素唯一?(删除不相邻的副本)

  •  34
  • aJ.  · 技术社区  · 17 年前

    我有一个向量包含几个非相邻的重复项。

    作为一个简单的例子,请考虑:

    2 1 6 1 4 6 2 1 1
    

    vector 唯一的方法是删除不相邻的重复项并保持元素的顺序。

    结果将是:

    2 1 6 4 
    

    我尝试的解决方案是:

    1. 插入std::set,但这种方法的问题是它会干扰元素的顺序。
    2. 手动消除重复:

          Define a temporary vector TempVector.
          for (each element in a vector)
          {
              if (the element does not exists in TempVector)
              {
                  add to TempVector;
              }
          }
          swap orginial vector with TempVector.
      

    我的问题是:

    是否有任何STL算法可以从向量中移除非相邻的重复项?它的复杂性是什么?

    11 回复  |  直到 17 年前
        1
  •  13
  •   fa.    17 年前

    我想你应该这样做:

    我将在向量上使用两个迭代器:

    当读取的数据不在集合中时,将其从第一个迭代器复制到第二个迭代器并递增。

    最后,只保留第二个迭代器之前的数据。

    复杂度为O(n.log(n)),因为重复元素的查找使用集合,而不是向量。

    #include <vector>
    #include <set>
    #include <iostream>
    
    int main(int argc, char* argv[])
    {
        std::vector< int > k ;
    
        k.push_back( 2 );
        k.push_back( 1 );
        k.push_back( 6 );
        k.push_back( 1 );
        k.push_back( 4 );
        k.push_back( 6 );
        k.push_back( 2 );
        k.push_back( 1 );
        k.push_back( 1 );
    
    {
        std::vector< int >::iterator r , w ;
    
        std::set< int > tmpset ;
    
        for( r = k.begin() , w = k.begin() ; r != k.end() ; ++r )
        {
            if( tmpset.insert( *r ).second )
            {
                *w++ = *r ;
            }
        }
    
        k.erase( w , k.end() );
    }
    
    
        {
            std::vector< int >::iterator r ;
    
            for( r = k.begin() ; r != k.end() ; ++r )
            {
                std::cout << *r << std::endl ;
            }
        }
    }
    
        2
  •  13
  •   CB Bailey    17 年前

    不用临时的 set 这样做可能会(可能)造成性能损失:

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

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

    对于较小的数据集,实现的简单性和所需的额外分配的缺乏可以抵消使用额外的 设置 . 但是,使用有代表性的输入进行测量是唯一确定的方法。

        3
  •  7
  •   Andreas Spindler    10 年前

    因为问题是“有没有STL算法。。。?它的复杂性是什么?”实现如下功能是有意义的 std::unique

    template <class FwdIterator>
    inline FwdIterator stable_unique(FwdIterator first, FwdIterator last)
    {
        FwdIterator result = first;
        std::unordered_set<typename FwdIterator::value_type> seen;
    
        for (; first != last; ++first)
            if (seen.insert(*first).second)
                *result++ = *first;
        return result;
    }
    

    所以这就是 标准::唯一 加上一个额外的集合。这个 unordered_set 会比普通的 set . 所有的元素都会被移除,这些元素与它们前面的元素相等(第一个元素会被保留,因为我们不能统一为零)。迭代器返回范围内的新端点 [first,last)

    编辑:最后一句话意味着容器本身没有被 unique . 这可能会让人困惑。下面的示例实际上将容器缩减为统一集。

    1: std::vector<int> v(3, 5);
    2: v.resize(std::distance(v.begin(), unique(v.begin(), v.end())));
    3: assert(v.size() == 1);
    

    第1行创建一个向量 { 5, 5, 5 } 独特的 distance resize 修剪向量。

        4
  •  6
  •   Community Mohan Dere    9 年前

    你可以在 fa's 答案使用 remove_copy_if

    class NotSeen : public std::unary_function <int, bool>
    {
    public:
      NotSeen (std::set<int> & seen) : m_seen (seen) { }
    
      bool operator ()(int i) const  {
        return (m_seen.insert (i).second);
      }
    
    private:
      std::set<int> & m_seen;
    };
    
    void removeDups (std::vector<int> const & iv, std::vector<int> & ov) {
      std::set<int> seen;
      std::remove_copy_if (iv.begin ()
          , iv.end ()
          , std::back_inserter (ov)
          , NotSeen (seen));
    }
    

    这对算法的复杂度没有影响(如文中所述,它也是O(n logn))。您可以使用无序集对此进行改进,或者如果值的范围足够小,您可以简单地使用数组或位数组。

        5
  •  3
  •   sbi    17 年前

    没有一个STL算法做你想做的事情来保持序列的原始顺序。

    你可以创建一个 std::set 一个比较谓词,它使用引用的数据而不是迭代器/索引对数据进行排序。然后从向量中删除集合中未引用的所有内容。(当然,你也可以用另一个 std::vector std::sort 和 std::unique 并以此作为保存内容的参考。)

        6
  •  3
  •   Heiko Schäfer    13 年前

    基于@fa的回答。它也可以用STL算法重写 std::stable_partition

    struct dupChecker_ {
        inline dupChecker_() : tmpSet() {}
        inline bool operator()(int i) {
            return tmpSet.insert(i).second;
        }
    private:
        std::set<int> tmpSet;
    };
    
    k.erase(std::stable_partition(k.begin(), k.end(), dupChecker_()), k.end());
    

    这样它更紧凑,我们不需要关心迭代器。

    似乎甚至没有引入太多的性能惩罚。我在我的项目中使用它,它需要处理相当大的 向量 常常是复杂的类型,这并没有真正的区别。

    另一个很好的特性是,可以调整 通过使用 std::set<int, myCmp_> tmpSet; . 例如,在我的项目中忽略某些舍入错误。

        7
  •  2
  •   Community Mohan Dere    11 年前

    http://www.builderau.com.au/program/java/soa/C-Removing-duplicates-from-a-range/0,339024620,320271583,00.htm

    https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-1052159.html

    不幸的是,约翰解决方案的完整代码似乎不再可用,约翰也没有回复五月的电子邮件。因此,我编写了自己的代码,基于与his类似的理由,但在某些细节上故意有所不同。如果你愿意的话,请随时联系我(vschoech think cell com)并讨论细节。

    #include <vector>
    #include <functional>
    
    #include <boost/bind.hpp>
    #include <boost/range.hpp>
    #include <boost/iterator/counting_iterator.hpp>
    
    /////////////////////////////////////////////////////////////////////////////////////////////
    // library stuff
    
    template< class Rng, class Func >
    Func for_each( Rng& rng, Func f ) {
        return std::for_each( boost::begin(rng), boost::end(rng), f );
    };
    
    template< class Rng, class Pred >
    Rng& sort( Rng& rng, Pred pred ) {
        std::sort( boost::begin( rng ), boost::end( rng ), pred );
        return rng; // to allow function chaining, similar to operator+= et al.
    }
    
    template< class T >
    boost::iterator_range< boost::counting_iterator<T> > make_counting_range( T const& tBegin, T const& tEnd ) {
        return boost::iterator_range< boost::counting_iterator<T> >( tBegin, tEnd );
    }
    
    template< class Func >
    class compare_less_impl {
    private:
        Func m_func;
    public:
        typedef bool result_type;
        compare_less_impl( Func func ) 
        :   m_func( func )
        {}
        template< class T1, class T2 > bool operator()( T1 const& tLeft, T2 const& tRight ) const {
            return m_func( tLeft ) < m_func( tRight );
        }
    };
    
    template< class Func >
    compare_less_impl<Func> compare_less( Func func ) {
        return compare_less_impl<Func>( func );
    }
    
    
    /////////////////////////////////////////////////////////////////////////////////////////////
    // stable_unique
    
    template<class forward_iterator, class predicate_type>
    forward_iterator stable_unique(forward_iterator itBegin, forward_iterator itEnd, predicate_type predLess) {
        typedef std::iterator_traits<forward_iterator>::difference_type index_type;
        struct SIteratorIndex {
            SIteratorIndex(forward_iterator itValue, index_type idx) : m_itValue(itValue), m_idx(idx) {}
            std::iterator_traits<forward_iterator>::reference Value() const {return *m_itValue;}
            index_type m_idx;
        private:
            forward_iterator m_itValue;
        };
    
        // {1} create array of values (represented by iterators) and indices
        std::vector<SIteratorIndex> vecitidx;
        vecitidx.reserve( std::distance(itBegin, itEnd) );
        struct FPushBackIteratorIndex {
            FPushBackIteratorIndex(std::vector<SIteratorIndex>& vecitidx) : m_vecitidx(vecitidx) {}
            void operator()(forward_iterator itValue) const {
                m_vecitidx.push_back( SIteratorIndex(itValue, m_vecitidx.size()) );
            }
        private:
            std::vector<SIteratorIndex>& m_vecitidx;
        };
        for_each( make_counting_range(itBegin, itEnd), FPushBackIteratorIndex(vecitidx) );
    
        // {2} sort by underlying value
        struct FStableCompareByValue {
            FStableCompareByValue(predicate_type predLess) : m_predLess(predLess) {}
            bool operator()(SIteratorIndex const& itidxA, SIteratorIndex const& itidxB) {
                return m_predLess(itidxA.Value(), itidxB.Value())
                    // stable sort order, index is secondary criterion
                    || !m_predLess(itidxB.Value(), itidxA.Value()) && itidxA.m_idx < itidxB.m_idx;
            }
        private:
            predicate_type m_predLess;
        };
        sort( vecitidx, FStableCompareByValue(predLess) );
    
        // {3} apply std::unique to the sorted vector, removing duplicate values
        vecitidx.erase(
            std::unique( vecitidx.begin(), vecitidx.end(),
                !boost::bind( predLess,
                    // redundand boost::mem_fn required to compile
                    boost::bind(boost::mem_fn(&SIteratorIndex::Value), _1),
                    boost::bind(boost::mem_fn(&SIteratorIndex::Value), _2)
                )
            ),
            vecitidx.end()
        );
    
        // {4} re-sort by index to match original order
        sort( vecitidx, compare_less(boost::mem_fn(&SIteratorIndex::m_idx)) );
    
        // {5} keep only those values in the original range that were not removed by std::unique
        std::vector<SIteratorIndex>::iterator ititidx = vecitidx.begin();
        forward_iterator itSrc = itBegin;
        index_type idx = 0;
        for(;;) {
            if( ititidx==vecitidx.end() ) {
                // {6} return end of unique range
                return itSrc;
            }
            if( idx!=ititidx->m_idx ) {
                // original range must be modified
                break;
            }
            ++ititidx;
            ++idx;
            ++itSrc;
        }
        forward_iterator itDst = itSrc;
        do {
            ++idx;
            ++itSrc;
            // while there are still items in vecitidx, there must also be corresponding items in the original range
            if( idx==ititidx->m_idx ) {
                std::swap( *itDst, *itSrc ); // C++0x move
                ++ititidx;
                ++itDst;
            }
        } while( ititidx!=vecitidx.end() );
    
        // {6} return end of unique range
        return itDst;
    }
    
    template<class forward_iterator>
    forward_iterator stable_unique(forward_iterator itBegin, forward_iterator itEnd) {
        return stable_unique( itBegin, itEnd, std::less< std::iterator_traits<forward_iterator>::value_type >() );
    }
    
    void stable_unique_test() {
        std::vector<int> vecn;
        vecn.push_back(1);
        vecn.push_back(17);
        vecn.push_back(-100);
        vecn.push_back(17);
        vecn.push_back(1);
        vecn.push_back(17);
        vecn.push_back(53);
        vecn.erase( stable_unique(vecn.begin(), vecn.end()), vecn.end() );
        // result: 1, 17, -100, 53
    }
    
        8
  •  2
  •   Max Lybbert    10 年前

    我的问题是:

    STL选项就是您提到的:将项目放入 std::set std::sort , std::unique 打电话来 erase() 在集装箱上。这两个都不能满足您的要求“删除不相邻的重复项并保持元素的顺序”

    那么为什么STL不提供其他选择呢?没有一个标准库能够满足每个用户的需求。STL的设计考虑包括“对几乎所有用户足够快”、“对几乎所有用户都有用”和“尽可能提供异常安全”(和“对标准委员会足够小”,因为Stepanov最初编写的库要大得多,stroostrup去掉了大约2/3的部分)。

    // Note:  an STL-like method would be templatized and use iterators instead of
    // hardcoding std::vector<int>
    std::vector<int> stable_unique(const std::vector<int>& input)
    {
        std::vector<int> result;
        result.reserve(input.size());
        for (std::vector<int>::iterator itor = input.begin();
                                        itor != input.end();
                                        ++itor)
            if (std::find(result.begin(), result.end(), *itor) == result.end())
                result.push_back(*itor);
            return result;
    }
    

    这个解应该是O(M*N),其中M是唯一元素的数目,N是元素的总数。

        9
  •  1
  •   Yelonek    17 年前

    据我所知,stl里没有。仰望 reference .

        10
  •  1
  •   winterlight    13 年前

    基于@Corden的答案,但使用lambda表达式并删除重复项,而不是将它们写入输出向量

        set<int> s;
        vector<int> nodups;
        remove_copy_if(v.begin(), v.end(), back_inserter(nodups), 
            [&s](int x){ 
                return !s.insert(x).second; //-> .second false means already exists
            } ); 
    
        11
  •  0
  •   Jonathan Mee    9 年前

    vector<int> foo remove 在这里为你做腿部运动,如果你想收缩向量,就用 erase 否则就用 last 当您希望删除重复项但保留顺序的向量时,请使用结束迭代器后面的一个:

    auto last = end(foo);
    
    for(auto first = begin(foo); first < last; ++first) last = remove(next(first), last, *first);
    
    foo.erase(last, end(foo));
    

    Live Example

    O(纳米) n个 是元素的数量和 是唯一元素的数目。就空间复杂性而言 O(n) 因为它会在适当的位置进行移除。

    推荐文章