获取迭代器范围的每个nth元素。

时间:2021-02-14 13:13:12

Is there any standard implementation (meaning stdlib or boost) of an iterator that wraps another iterator and gives only each nth element of it?

是否存在一个迭代器的标准实现(即stdlib或boost)来包装另一个迭代器并只给出它的第n个元素?

I first thought this would be possible with a fitting predicate and boost::filter_iterator, but the predicate gets only the value and not the base iterator, so it cannot tell the distance to the start.

我最初认为有了一个合适的谓词和boost::filter_iterator,这是可能的,但是谓词只获得值,而不是基迭代器,所以它不能告诉起始的距离。

Edit
To give some more information: The iterator should be compatible with functions like std::transform or std::copy. So it should be used like stdlib iterators.

编辑以提供更多信息:迭代器应该与std:::transform或std::copy等函数兼容。所以它应该像stdlib迭代器一样使用。

Similar questions:
C++/STL: std::transform with given stride?
Non-unit iterator stride with non-random access iterators

类似的问题:C++/STL: std::用给定的步法转换?非随机访问迭代器的非单元迭代器。

2 个解决方案

#1


9  

Boost.Range provides a stride adaptor. Using boost::begin/boost::end would net you the associated iterators.

提振。Range提供一个跨接适配器。使用boost:::begin/boost::end将为您提供相关的迭代器。

#2


5  

You can use boost::filter_iterator with predicate like:

您可以使用boost::filter_iterator,其谓词为:

 template< typename T, int N >
 struct EveryNth {
    bool operator()(const T&) { return m_count++ % N == 0; }
    EveryNth() : m_count(0) {}
    private:
      int m_count;
 };

#1


9  

Boost.Range provides a stride adaptor. Using boost::begin/boost::end would net you the associated iterators.

提振。Range提供一个跨接适配器。使用boost:::begin/boost::end将为您提供相关的迭代器。

#2


5  

You can use boost::filter_iterator with predicate like:

您可以使用boost::filter_iterator,其谓词为:

 template< typename T, int N >
 struct EveryNth {
    bool operator()(const T&) { return m_count++ % N == 0; }
    EveryNth() : m_count(0) {}
    private:
      int m_count;
 };