Python-like iterator idioms in C++

Viewed 151

Python has interesting ways to combine and build iterators (see itertools). I am particularly interested in the functionality of repeat, cycle and chain. Other iterators there are also interesting.

Are these iterators implemented in C++ or boost? I found Boost's adaptors, but I don't think it would be possible to implement the iterators repeat, cycle and chain.

I can of course write my own iterator classes for these (and others in itertools), but I wanted to check that this wheel hasn't already been invented.

1 Answers

Well, you can just implement it in C++. Here is example:

#include <iostream>
#include <vector>


template <typename It, typename T = typename It::value_type>
class cycle_iterator
{
public:
    typedef cycle_iterator self_type;
    typedef T value_type;
    typedef T& reference;
    typedef T* pointer;
    typedef std::forward_iterator_tag iterator_category;
    typedef int difference_type;
    cycle_iterator(It begin, It end) : m_current(begin), m_begin(begin), m_end(end) { }
    self_type operator++() { advance(); return *this; }
    self_type operator++(int) { self_type i = *this; advance(); return i; }
    reference operator*() { return *m_current; }
    pointer operator->() { return &*m_current; }
    bool operator==(const self_type& rhs) { return m_current == rhs.m_current; }
    bool operator!=(const self_type& rhs) { return m_current != rhs.m_current; }

private:
    void advance() {
        ++m_current;

        if (m_current == m_end)
            m_current = m_begin;
    }

private:
    It m_current;
    It m_begin, m_end;
};


int main()
{
    std::vector<int> vec {1, 2, 3, 4};

    cycle_iterator<std::vector<int>::iterator> it (vec.begin(), vec.end());

    for (int i = 0; i < 10; i++)
        std::cout << *it++ << " ";

    std::cout << std::endl;
    return 0;
}

Resulting output:

1 2 3 4 1 2 3 4 1 2

Be careful, it's endless.

Actually, if you want - you can implement non-endless variant if you wish (and as you wish), this is just simple demo.

Related