繰り返し値を出します。
template<typename T> class cCycle : public cIterable<T> { shared_ptr<cIterable<T>> gen; vector<T> v; typename vector<T>::const_iterator p; bool first; public: cCycle(shared_ptr<cIterable<T>> g) : gen(g), first(true) { } bool exists_next() { if(first) { if(gen->exists_next()) { v.push_back(gen->value()); } else { first = false; if(v.empty()) return false; p = v.begin(); } } else { if(++p == v.end()) p = v.begin(); } return true; } T value() const { return first ? gen->value() : *p; } }; template<typename T> shared_ptr<cIterable<T>> cycle(shared_ptr<cIterable<T>> g) { return shared_ptr<cIterable<T>>(new cCycle<T>(g)); }
2回目以降は、vectorに入れた値を使っています。
int main() { auto g = zip(count(), cycle(range(4))); auto f = [](tuple<int,int> x) { return fst(x) < 10; }; cout << map(snd<int,int>, takewhile(f, g)) << endl; }
0 1 2 3 0 1 2 3 0 1