Boost logo

Boost Users :

From: Jaakko Järvi (jarvi_at_[hidden])
Date: 2006-11-29 22:48:50


On Nov 27, 2006, at 1:14 AM, Haroon Khan wrote:

> Hi,
> I'm experimenting with the boost lambda library, and I wrote the
> following code, to go through the vector of numbers and print out
> statements if the number is greater than 5 or less than 5
>
> int a[]={1,2,3,4,5,6,7,8,9,10,10,9,8,4,7,6,5,4,3,3,1};
> std::vector<int> v(a,a+sizeof(a)/sizeof(int));
> std::for_each
> ( v.begin()
> , v.end()
> , (if_(_1<5)[
> std::cout<<var((boost::format("%d is less than
> 5\n")%_1).str())
> ].else_[
> std::cout<<var((boost::format("%d is greater than
> 5\n")%_1).str())
> ]) );
>
> The boost::basic_format::operator % code gives an
> assertion since
> the object that is being passed is the placeholder object, and not
> the current value. Is there a correct way of doing this?

There is, but it is kind of complicated.
Lambda Library gets kind of hairy with more complex lambda expressions:

#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>
#include <boost/format.hpp>
#include <boost/lambda/if.hpp>
#include <boost/lambda/construct.hpp>
#include <iostream>

using namespace boost::lambda;
int main() {

int a[]={1,2,3,4,5,6,7,8,9,10,10,9,8,4,7,6,5,4,3,3,1};
std::vector<int> v(a,a+sizeof(a)/sizeof(int));
std::for_each
    ( v.begin(), v.end(),
      (if_(_1<5)[
                  std::cout <<
                    ret<boost::format>(bind(constructor<boost::format>(), "%d is
less than 5\n") % _1)
               ].else_[
                  std::cout <<
                    ret<boost::format>(bind(constructor<boost::format>(), "%d is
greater than 5\n") % _1)
               ]) );
}

The bind(constructor<boost::format>(), ...) is necessary, because you
really need to construct a new
format object at every iteration, otherwise the format library throws
an exception saying you
are trying to pass to many parameters to a format object, more that
what is specfied in the format string.

the ret<boost::format>(...) is needed to tell lambda what the return
type of format's operator% is.

All in all, the above lambda is complex enough that writing a
function object explicitly might be
more justified... at least until we have built-in lambdas, if that
ever happens.

Cheers,

   Jaakko

>
> Thanks, Haroon
> _______________________________________________
> Boost-users mailing list
> Boost-users_at_[hidden]
> http://lists.boost.org/mailman/listinfo.cgi/boost-users


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net