STL容器如何折叠?
我需要一个类似于 Haskell 的 foldl
函数来折叠任何 STL 容器。预期的签名如下:
template Iterator, FoldingFunction, Result
Result foldl(
Iterator begin,
Iterator end,
FoldingFunction f,
Result initValue);
标准STL没有这样的功能。 Boost 有吗?
我知道它实现起来非常简单,但我想知道是否有任何现成的标准化实现。
还有一个问题:您通常如何在 C++/STL 中折叠数据列表?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
STL确实有这样的功能:
std::accumulate
。但是,它位于标头
中,而不是
中。实际上关于“Fold”的维基百科页面已经列出了
foldl
/foldr
适用于大多数编程语言,包括 C++。STL does have such a function:
std::accumulate
. However, it is in the header<numeric>
, not<algorithm>
.Actually the Wikipedia page on "Fold" already listed the
foldl
/foldr
functions on most programming languages, including C++.您是否看过 std::accumulate 中的 标头?
Have you looked at std::accumulate in the
<numeric>
header?这是我使用 std::accumulate 实现的
reduce
意思是 Haskell 中的折叠。而且这个函数模板可能会让程序的功能更加丰富:)here's my implementation using std::accumulate
the
reduce
means fold in Haskell. And this function template may make the program more functional :)尽管
std::accumulate
似乎是最好的候选者,但我认为使用旧的for_each
也可以实现该要求。我从KennyTM的答案中的链接中获取了示例,并且全部翻译了
到
for_each
。 完整代码发布在键盘上,以下是一些摘录:Although
std:: accumulate
seems to be the best candidate, I think that the requirement can be achieved by using good oldfor_each
too.I took the examples from the link in the answer of KennyTM, and translated all of them
to
for_each
. The full code is posted at codepad, following is some excerpt:为什么不只是;
或递归地; // 也许你可以帮助我正确的语法...
why not just;
or recursively; // maybe you could help me with the correct syntax...