【问题标题】:Python-like iterator idioms in C++C++ 中类似 Python 的迭代器习惯用法
【发布时间】:2020-11-21 10:54:07
【问题描述】:

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

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

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

【问题讨论】:

  • 这些在range-v3 中可用。它还允许您编写自己的范围适配器。
  • itertools的cpp实现

标签: python c++ boost iterator


【解决方案1】:

嗯,你可以在 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;
}

结果输出:

1 2 3 4 1 2 3 4 1 2

小心,没完没了。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-02
    • 2017-12-21
    • 1970-01-01
    • 1970-01-01
    • 2022-12-13
    • 2017-04-19
    • 2012-03-11
    • 1970-01-01
    相关资源
    最近更新 更多