繁体   English   中英

C++ 中的类似 Python 的迭代器习惯用法

[英]Python-like iterator idioms in C++

Python 有有趣的方法来组合和构建迭代器(参见itertools )。 我对repeatcyclechain的功能特别感兴趣。 其他迭代器也很有趣。

这些迭代器是在 C++ 还是 boost 中实现的? 我找到了 Boost 的适配器,但我认为不可能实现迭代器repeatcyclechain

我当然可以为这些(以及其他在itertools中的)编写自己的迭代器类,但我想检查这个轮子是否还没有被发明。

好吧,你可以在 C++ 中实现它。 这是示例:

#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;
}

结果 output:

1 2 3 4 1 2 3 4 1 2

小心,没完没了。

实际上,如果您愿意 - 如果您愿意(并且如您所愿),您可以实现非无限变体,这只是简单的演示。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM