Demps
Demps

Reputation: 117

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!

Upvotes: 0

Views: 778

Answers (2)

Manuel
Manuel

Reputation: 13119

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();

Upvotes: 1

GManNickG
GManNickG

Reputation: 504333

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.

Upvotes: 1

Related Questions