中有函数组合的东西吗?
我想要做的事情可以使用 C++0x lambda 轻松完成。我只是想弄清楚如何仅使用 bind1st
和 bind2nd
来做到这一点。
我需要找到向量 v
中的第一个元素 i
,使得 (i-1)/p1 == p2
其中 p1 和 p2是预定义的整数。
find_if(v.begin(), v.end(), ???)
我不知道如何使用 minus
divides
equal_to
和 bind2nd 构成谓词
。看来我需要一些功能组合
equal(div(minus(i, 1), p1), p2)
可以吗?
请不要提出解决方法,例如使用 operator()
编写独立的一元函数或结构体。我对函数式函子机制以及 bind1st
和 bind2nd
非常感兴趣。这不是为了真正的代码,只是兴趣。谢谢 :)
What I want to do is done pretty easily with C++0x lambdas. I just want to figure out how to do it with bind1st
and bind2nd
only.
I need to find the first element i
in the vector v
, such that (i-1)/p1 == p2
where p1 and p2 are predefined integers.
find_if(v.begin(), v.end(), ???)
I can't figure out how to form the predicate with minus<int>
divides<int>
equal_to<int>
and bind2nd
. Seems like I need some function composition
equal(div(minus(i, 1), p1), p2)
Is it possible?
Please don't suggest workarounds such as writing a freestanding unary function or a struct with operator()
. I am really interested in mechanics of functors in functional along with bind1st
and bind2nd
. This is not for real code, just interest. Thanks :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不幸的是,仅使用当前的
功能
库无法实现您想要做的事情。您需要创建自己的类或函数来进行组合。Boost 曾经提供了一个 Compose 库,用于组合这样的函数,但我认为在引入 Bind 和 Lambda 时它被删除了。
为了完整起见,可以使用类似以下内容的
bind
来完成:Unfortunately, what you're trying to do is not possible with only the current
functional
library. You would need to create your own class or function to do the composition.Boost used to offer a Compose library that was used to compose functions like this, but I think it was removed when Bind and Lambda were introduced.
And just for the sake of completion, it can be done with
bind
using something like:如果你可以在方程的左侧拉起
i
,那么我猜你不需要完全组合。即 i == p1*p2+1
。但如果你坚持按照自己的表达方式进行创作,那么 @dauphic 的答案就是你的最佳选择。
If you can pull up
i
on the left hand side of equation then you don't need to compose altogether i guess.i.e. i == p1*p2+1
.But if you insist on composing the way your expression is then @dauphic's answer is the one to go for.