Skipping iterator

前端 未结 3 497
醉话见心
醉话见心 2020-12-07 01:05

I have a sequence of values that I\'d like to pass to a function that takes a (iterator begin, iterator end) pair. However, I only want every second element in

3条回答
  •  北海茫月
    2020-12-07 01:31

    struct TrueOnEven {
     template< typename T >
     bool operator()(const T&) { return mCount++ % 2 == 0; }
     TrueOnEven() : mCount(0) {}
     private:
      int mCount;
    };
    
    int main() {
     std::vector< int > tVec, tOtherVec;
     ...
     typedef boost::filter_iterator< TrueOnEven, int > TakeEvenFilterType;
    
     std::copy( 
      TakeEvenFilterType(tVec.begin(), tVec.end()),
      TakeEvenFilterType(tVec.end(), tVec.end()),
      std::back_inserter(tOtherVec));
    }
    

    To be honest, this is anything else than nice and intuitive. I wrote a simple "Enumerator" library including lazy integrated queries to avoid hotchpotch like the above.. It allows you to write:

    Query::From(tVec.begin(), tVec.end())
    .Skip<2>()
    .ToStlSequence(std::back_inserter(tOtherVec));
    

    where Skip<2> basically instantiates a generalized "Filter" which skips every N-th (in this case every second) element...

    Cheers,

    Paul

提交回复
热议问题