Lazy变换在C ++ [英] Lazy transform in C++
问题描述
我有以下的Python代码片段,我想使用C ++重现:
I have the following Python snippet that I would like to reproduce using C++:
from itertools import count, imap
source = count(1)
pipe1 = imap(lambda x: 2 * x, source)
pipe2 = imap(lambda x: x + 1, pipe1)
sink = imap(lambda x: 3 * x, pipe2)
for i in sink:
print i
我听说过 Boost Phoenix a>,但我找不到一个懒惰的例子 transform
的行为与Python的 imap
相同。
I've heard of Boost Phoenix, but I couldn't find an example of a lazy transform
behaving in the same way as Python's imap
.
编辑:为了澄清我的问题,这个想法不仅是使用为
按顺序应用函数,而是能够在无限生成器上使用 std :: transform
的算法。
to clarify my question, the idea is not only to apply functions in sequence using a for
, but rather to be able to use algorithms like std::transform
on infinite generators. The way the functions are composed (in a more functional language like dialect) is also important, as the next step is function composition.
更新:感谢bradgonesurfing,David Brown,和Xeo的惊人答案!我选择了Xeo's,因为它是最简洁的,它让我在我想成为的地方,但大卫是非常重要的通过的概念。此外,bradgonesurfing的提示Boost :: Range:)。
Update: thanks bradgonesurfing, David Brown, and Xeo for the amazing answers! I chose Xeo's because it's the most concise and it gets me right where I wanted to be, but David's was very important into getting the concepts through. Also, bradgonesurfing's tipped Boost::Range :).
推荐答案
int main(){
auto map = boost::adaptors::transformed; // shorten the name
auto sink = generate(1) | map([](int x){ return 2*x; })
| map([](int x){ return x+1; })
| map([](int x){ return 3*x; });
for(auto i : sink)
std::cout << i << "\n";
}
这篇关于Lazy变换在C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!