template lt;class T, class FAdd, class FElemgt; T For(int from, int to, FAdd fAdd, FElem fElem)
{
assert(to gt;= from);
T sum = fElem(from);
for (int i = from + 1; i lt;= to; i++)
sum = fAdd(sum, fElem(i));
return sum;
}

数学上面我们常看到这样的符号,比如:

这两个分别是求一串式子的和,和一串的集合的并。

类似地,我们可以从求和、求并,推广到任意的二参数运算(或二参数函数)

比如推广到字符串加


再比如更复杂的,字符串之间以 quot;,quot; 相连,例如我们要生成一个表示一个数组的字符串,
例如 to_str(x[0]) + quot;,quot; + to_str(x[1]) + quot;,quot; +... + quot;,quot; + to_str(x[n-1])


这个计算,用我们在本文开头定义的 For 函数可以写成:
str add(str a, str b) { return a + quot;,quot; + b; }
For(0, n-1, add, [](int i){ return to_str(x); })
// 或者:
For(0, n-1, [](str a, str b) { return a + quot;,quot; + b; }, [](int i) { return to_str(x); })

PS. 有时候考虑到性能,我们还可以有一种变种版本:

template lt;class T, class Fgt; T For(int from, int to, T sum0, F f)
{
if (to lt; from)
return sum0;

T sum = sum0;
for (int i = from; i lt;= to; i++)
sum = f(sum, i);
return sum;
}

这里的 f 就是上面的 fAdd(求和) 和 fElem(求第i个元素) 的复合函数,
比如上面的那个计算可以改写成:
For(0, n-1, quot;quot;, [](ptrlt;strgt; pSum, int i) { *pSum += to_str(x); return pSum; })

不过必须注意,这种情况下,参数 sum0 必须为你那个(T上的)quot;加法quot;运算的quot;单位元quot;,或者是被quot;加quot;的第一个元素。
举个典型的例子,计算 a[0] * a[1] * ... * a[n-1]
如果写成 For(0, n-1, 0, [](float product, int i) { return product * a; })
这样就错了!
应当写成 For(0, n-1, 1, [](float product, int i) { return product * a; }),
或者 For(1, n-1, a[0], [](float product, int i) { return product * a; }).
锐亚教育

锐亚教育,游戏开发论坛|游戏制作人|游戏策划|游戏开发|独立游戏|游戏产业|游戏研发|游戏运营| unity|unity3d|unity3d官网|unity3d 教程|金融帝国3|8k8k8k|mcafee8.5i|游戏蛮牛|蛮牛 unity|蛮牛