python - C++ 中类似 Python 的迭代器习惯用法
问题描述
Python 有一些有趣的方法来组合和构建迭代器(参见itertools)。我对 和 的功能repeat
特别cycle
感兴趣chain
。其他迭代器也很有趣。
这些迭代器是用 C++ 还是 boost 实现的?我找到了 Boost 的适配器,但我认为不可能实现迭代repeat
器cycle
和chain
.
我当然可以为这些(以及 中的其他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;
}
结果输出:
1 2 3 4 1 2 3 4 1 2
小心,没完没了。
实际上,如果您愿意 - 如果您愿意(并且如您所愿),您可以实现非无限变体,这只是简单的演示。