@
c0xt30a 是 lazy 的。针对你的例子,
1. 第一个遍历 container 的操作就是翻译成
for (auto& i : container) {
...
}
2. 第二个 take_first(3)的操作是翻译成
num = 3
...
if (num-- != 0) {
...
} else {
break
}
...
3. 第三个 max_reduce 的操作就是翻译成
max = std::nullopt
...
if (!max || *max < x) {
max = x
}
然后把所有逻辑嵌套起来之后,就是下面这样:
num = 3
max = std::nullopt
for (auto& i : container) {
if (num-- != 0) {
if (!max || *max < i) {
max = i
}
} else {
break
}
}
按照你的例子,我弄了一个新的 example (
https://github.com/zzxx-husky/coll/blob/master/examples/first_n_max.cpp )。虽然不是遍历一个 container,但是也是试图 生成 很多的整数。因为只需要从前 3 个里面找,所以最后其实只生成了 3 个整数。下面是在 WSL 上运行 3 次的结果。
zzxx@zzxx:~/repos/coll/release | master
$ time ./examples/FirstNMax
Int 1 is 463223032
Int 2 is 1934040530
Int 3 is 897990617
The max of the 3 ints is 1934040530
real 0m0.010s
user 0m0.000s
sys 0m0.016s
zzxx@zzxx:~/repos/coll/release | master
$ time ./examples/FirstNMax
Int 1 is 2009885599
Int 2 is 491657854
Int 3 is 58190656
The max of the 3 ints is 2009885599
real 0m0.010s
user 0m0.000s
sys 0m0.000s
zzxx@zzxx:~/repos/coll/release | master
$ time ./examples/FirstNMax
Int 1 is 1704636435
Int 2 is 1382089679
Int 3 is 1782466259
The max of the 3 ints is 1782466259
real 0m0.010s
user 0m0.000s
sys 0m0.000s