【发布时间】:2020-06-15 01:18:59
【问题描述】:
我已经阅读了一些类似的问题,但我没有找到我正在寻找的确切内容。
在纯数学方式中,列表递归定义为:(head, rest)。
其中head 是列表中的第一个元素,rest 是一个列表。
因此例如 (1,2,3,4) 表示为 (1, (2,(3,(4,[])))) 其中[] 是空列表。
然后,如果我们想遍历列表,我们可以或多或少地编写一个递归函数,如下所示:
iterate(list)
head = list.head
// do stuff and return if head is the empty element
iterate(list.rest)
如果我们想迭代每两个元素:
pair_iterate(list)
head1 = list.head
head2 = list.rest.head
// do stuff and return if head is the empty element
iterate(list.rest.rest)
我正在尝试在 C++ 中实现第二种行为。
在 C++ 17 中,引入了折叠,因此可以执行以下操作:
template<typename...types>
auto sum(types...values) {
return (... + values);
}
但是假设我们想要相邻参数的乘积之和,例如sum(1,2,3,4)
是1*2 + 3*4。
在这种情况下,我们需要“折叠两次”以使 2 个头执行操作并传递列表的其余部分。类似于我的伪代码。
有人对如何连续获得 2 折有建议吗?
编辑: 我特别想用折叠来做,即在函数声明中,而不必依赖递归模板函数。
【问题讨论】:
-
@cigien 我认为这不是真的。起始状态 (1,2,3,4)。获取第一个关闭状态为 (1) (2,3,4),获得第二个关闭状态为 (1)(2)(3,4) 第一次递归计算 1 * 2。在列表中调用自身 (3 ,4)。弹出 2 个头,我们计算 3 * 4。然后我们将它们加在一起,我们得到 (1*2) + (3*4)。除非我查错了代码。
-
不,没关系,只是检查一下,谢谢。
标签: c++ templates variadic-templates fold