你可以像这样滚动自己:
#include <array>
#include <iostream>
#include <functional>
template <class T>
struct no_op : std::unary_function <T,bool>
{
bool operator() (const T& x) const
{
return x;
}
};
template <class ItSource,
class ItPredicate,
class PredMod = no_op<bool> >
class ConditionalIterator
{
ItSource _srcBegin;
ItSource _srcEnd;
ItPredicate _predBegin;
ItPredicate _predEnd;
void MoveNext()
{
while (_predBegin != _predEnd &&
_srcBegin != _srcEnd &&
PredMod()(!*_predBegin))
{
++_predBegin;
++_srcBegin;
}
}
public:
typedef ConditionalIterator & Reference;
typedef typename std::iterator_traits<ItSource>::value_type ValueType;
ConditionalIterator(ItSource srcBegin, ItSource srcEnd,
ItPredicate predBegin, ItPredicate predEnd)
: _srcBegin(srcBegin)
, _srcEnd(srcEnd)
, _predBegin(predBegin)
, _predEnd(predEnd)
{
MoveNext();
}
ConditionalIterator(ConditionalIterator const &other)
: _srcBegin(other._srcBegin)
, _srcEnd(other._srcEnd)
, _predBegin(other._predBegin)
, _predEnd(other._predEnd)
{
}
ConditionalIterator &operator=(ConditionalIterator const &other)
{
if (this != &other)
{
_srcBegin = other._srcBegin;
_srcEnd = other._srcEnd;
_predBegin = other._predBegin;
_predEnd = other._predEnd;
}
return (*this);
}
Reference operator++()
{
++_predBegin;
++_srcBegin;
MoveNext();
return (*this);
}
ConditionalIterator operator++(int)
{
ConditionalIterator cit = *this;
operator++();
return (cit);
}
operator bool() const
{
return (_srcBegin != _srcEnd &&
_predBegin != _predEnd);
}
ValueType operator*()
{
return (*_srcBegin);
}
};
template <class PredMod, class ItSource, class ItPred>
ConditionalIterator<ItSource, ItPred, PredMod> MakeConditionalIterator(ItSource srcBegin, ItSource srcEnd,
ItPred predBegin, ItPred predEnd)
{
return (ConditionalIterator<ItSource, ItPred, PredMod>(srcBegin, srcEnd, predBegin, predEnd));
}
此代码远未完成,但它应该可以帮助您入门。然后你像这样使用它:
int main()
{
std::array<int,5> element={ 1 , 2 , 4 , 8 , 10 };
std::array<bool,5> deleted={ false, true, false, false, true };
auto cit_valid = MakeConditionalIterator<std::logical_not<bool> >(element.begin(), element.end(),
deleted.begin(), deleted.end());
auto cit_delete = MakeConditionalIterator<no_op<bool> >(element.begin(), element.end(),
deleted.begin(), deleted.end());
while (cit_delete)
{
std::cout << *cit_delete++ << std::endl;
}
while (cit_valid)
{
std::cout << *cit_valid++ << std::endl;
}
return (0);
}