How to make elements of vector unique? (remove non adjacent duplicates)

后端 未结 11 1023
醉梦人生
醉梦人生 2020-11-29 05:01

I have a vector containing few non-adjacent duplicates.

As a simple example, consider:

2 1 6 1 4 6 2 1 1

I am trying to make this

11条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-29 05:31

    You can remove some of the loops in fa's answer using remove_copy_if:

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

    This has no affect on the complexity of the algorithm (ie. as written it's also O(n log n)). You can improve upon this using unordered_set, or if the range of your values is small enough you could simply use an array or a bitarray.

提交回复
热议问题