泛型算法unique_copy
vector <SA> vec1;
vector <SA> vec2;vec2.sort(); 
unique_copy(vec2.begin(),vec2.end(),back_inserter(vec1));这样复制添加,vec1与vec2,如果有相同项,是同时存在,还是不复制vec2中相同的项?

解决方案 »

  1.   

    template <class InputIterator, class OutputIterator>
      OutputIterator unique_copy ( InputIterator first, InputIterator last,
                                   OutputIterator result )
    {
      *result=*first;
      while (++first != last)
      {
        if (!(*result == *first))  // or: if (!pred(*result,*first)) for the pred version
          *(++result)=*first;
      }
      return ++result;
    }
    back_inserter调用的push_back成员函数,因此,如果vec1中原来有元素,将不会清空~~
    简言之就是vec1原来有什么东西完全不影响结果。
      

  2.   


    谢谢,继续请教,如何我想消除vec1与vec2中相同项,是否有简便方法?是否只能先添加ec2到vec1,再对vec1排序,消除重复项?
      

  3.   


    template <class Type>
    void Dis(const Type& e)
    {
    typename Type::const_iterator beg(e.begin()),end(e.end());
    for(;beg!=end;++beg)
    {
    std::cout<<*beg<<' ';
    }
    std::cout<<'\n';
    }
    int main()
    {
    int first[] = {5,10,15,20,25};
    int second[] = {50,40,30,20,10};
    std::vector<int> v;                           // 0  0  0  0  0  0  0  0  0  0 std::sort (first,first+5);     //  5 10 15 20 25
    std::sort (second,second+5);   // 10 20 30 40 50 std::set_difference (first, first+5, second, second+5, std::back_inserter(v)); Dis(v); return 0;
    }
      

  4.   

    谢谢!我原不知泛型有set_difference 这么多功能,照楼上指点,我需要的是:Set_union