为第二个范围内的重复设置差异,替代 remove_copy

Umu*_*bak 6 c++ stl

我有两个数组或向量,比如:

  int first[] = {0,0,1,1,2,2,3,3,3};
  int second[] = {1,3};
Run Code Online (Sandbox Code Playgroud)

我想摆脱第一组中的 1s 和 3s,set_difference只能摆脱这些值的第一次出现,但这不是我想要的。

我是否应该通过在第二个范围上迭代并每次从第一组中删除一个条目来使用remove_copy执行此操作。

在 C++ 中执行此操作的最佳方法是什么?

Mar*_*utz 2

写一个专门的set_difference:

template <typename InputIterator1, typename InputIterator2, typename OutputIterator>
OutputIterator set_difference_any( InputIterator1 first1, InputIterator1 last1,
                                   InputIterator2 first2, InputIterator2 last2,
                                   OutputIterator result )
{
  while ( first1 != last1 && first2 != last2 )
    if ( *first1 < *first2 ) {
      *result = *first1;
      ++first1;
      ++result;
    } else if ( *first2 < *first1 ) {
      ++first2;
    } else {
      ++first1;
      //++first2; // this is the difference to set_difference
    }
  return std::copy( first1, last1, result );
}
Run Code Online (Sandbox Code Playgroud)

然后将其应用到问题中:

#include "set_difference_any.h"
#include <boost/range.hpp>
#include <iterator>
#include <vector>

std::vector<int> result;
set_difference_any( boost::begin( first ), boost::end( first ),
                    boost::begin( second ), boost::end( second ),
                    std::back_inserter( result ) );
Run Code Online (Sandbox Code Playgroud)

该算法是线性的(最大last1-first1 + last2-first2比较)