当前位置: 动力学知识库 > 问答 > 编程问答 >

boost - c++ transform with if_then_else control structure

问题描述:

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!

网友答案:

if_then_else in your usage is incorrect, in the same way this is:

int i = if (some_condition){ 0; } else { 1; };

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 a for_each loop, where you'd take one action or the other depending on a condition. The if_then_else_return is for a ternary conditional.

网友答案:

Since you already use Boost I recommend BOOST_FOREACH instead of such a complex lambda expression:

BOOST_FOREACH(int & i, v)
    i = rand() % ratio ? i : rand();

This will be very easy to adapt once the new range-based for loop becomes available:

for(int & i : v)
    i = rand() % ratio ? i : rand();
分享给朋友:
您可能感兴趣的文章:
随机阅读: