开发者

How to use a sequence of statements in Boost.Phoenix together with std::transform?

I'd like to use Boost.Phoenix to create a lambda function that consists of a few lines of code and then "returns" a value so I can use it together with std::transform.

Like this:

std::transform(a.begin(), a.end(), b.begin(),
        (
            //Do something complicated here with the elements of a:
            statement1,
            statement2,
            statement3
            //Is there a way to return a value here?
        )
        );

With std::for_each this would work perfectly, but with std::transform it does not compile because the comma operator returns void. How can I return a value from a lambda function like this?


Edit: I changed the code开发者_运维技巧 fragment because what I wrote in the first place led to misunderstandings about what I want to do.


No, this isn't possible. From the Boost.Phoenix v2 statement docs:

Unlike lazy functions and lazy operators, lazy statements always return void.

(Note that this same assertion is in the Boost.Phoenix v3 docs as well.)


In functional programming, it's not the intention to change state. However, instead of using for_each, you may use accumulate. Accumulating implies you have a 'starting value' (e.g. m=1,n=0), and a function that 'adds' a value to an output value:

#include <vector>

struct MN { int m, n; 
  MN(int m,int n):m(m),n(n){}
  static MN accumulate( MN accumulator, int value ) {
     return MN( accumulator.m + value, accumulator.n * value );
  }
}; // your 'state'

int main(){
  std::vector<int> v(10,10); // { 10, 10, ... }
  MN result = std::accumulate( v.begin(), v.end(), MN(0,1), MN::accumulate );
  printf("%d %d", result.m, result.n );
}

I'm unfamilar with Phoenix, but probably there is a way to define the MN::accumulate function in terms of it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜