c++使用 if_then_else 控制结构进行变换
我正在尝试使用 Boost Lambda 中的变换和 if_then_else 控制结构来更改向量中的整数值。然而我的编译器并不欣赏我的努力。我尝试的代码是:
transform(theVec.begin(), theVec.end(), theVec.begin(),
if_then_else(bind(rand) % ratio == 0, _1 = bind(rand) % maxSize, _1));
我尝试将其简化为以下内容:
transform(theVec.begin(), theVec.end(), theVec.begin(),
if_then_else(0 == 0, _1 = MaxIntSizeCFG, _1));
但编译器告诉我:没有匹配的函数可用于调用 'if_then_else(.........................' 我读到控制结构的返回值是无效的,那么我在这种情况下尝试的使用完全错误吗?
预先感谢您的宝贵时间!
I'm trying to change the integer values in a vector using transform and an if_then_else control structure from Boost Lambda. However my compiler is not appreciating my efforts. The code I am attempting is:
transform(theVec.begin(), theVec.end(), theVec.begin(),
if_then_else(bind(rand) % ratio == 0, _1 = bind(rand) % maxSize, _1));
I tried simplifying it to the following:
transform(theVec.begin(), theVec.end(), theVec.begin(),
if_then_else(0 == 0, _1 = MaxIntSizeCFG, _1));
but the compiler tells me: no matching function for call to 'if_then_else(..........'
I read that the return values from control structures is void, so is my attempted usage in this case entirely wrong?
Thanks in advance for your time!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的用法中的
if_then_else
是不正确的,就像这样:您想要的只是三元运算符;然而,这在 lambda 中不起作用。您可以使用
if_then_else_return
结构来模拟这一点。 (即,您已经很接近了!)if_then_else
用于类似for_each
循环,您可以根据条件采取一个或另一个操作。if_then_else_return
用于三元条件。if_then_else
in your usage is incorrect, in the same way this is:What you want is merely the ternary operator; however, this won't work in a lambda. You can simulate this with the the
if_then_else_return
structure instead. (i.e., you were close!)The
if_then_else
is for something like afor_each
loop, where you'd take one action or the other depending on a condition. Theif_then_else_return
is for a ternary conditional.由于您已经使用了 Boost,我建议使用 BOOST_FOREACH 而不是如此复杂的 lambda 表达式:
一旦新的基于范围的 for 循环可用,这将非常容易适应:
Since you already use Boost I recommend BOOST_FOREACH instead of such a complex lambda expression:
This will be very easy to adapt once the new range-based for loop becomes available: