|
Boost Users : |
From: Stuart Dootson (stuart.dootson_at_[hidden])
Date: 2005-09-27 08:22:56
On 9/27/05, Alexander Borghgraef <alexander.borghgraef.rma_at_[hidden]> wrote:
>
>
> On 9/26/05, jarvi <jarvi_at_[hidden]> wrote:
> > the var function makes a lambda functor out of a variable, so you can
> > write the expression as:
> >
> > var(n) = _1
>
> Thanks, I should have seen that one in the manual. Posting at the end of
> a work day is
> obviously not a good idea :-) I've got another lambda related question
> though. My example was
> a useless simplification, what I'm really trying to do is to read data from
> a container v into a legacy
> matrix class which doesn't have an iterator. I can do this with a for loop:
>
> std::vector<char> v;
> MyMatrix<char> m; // Has h and w members for height and width, and
> element access using operator()( int i, int j )
> std::vector<char>::iterator v_it = v.begin();
> for ( long c = 0; c < m.h * m.w; ++c )
> {
> m( c / m.w , c % m.w ) = *v_it;
> ++v_it;
> }
>
> This works perfectly. I figured it should be possible to do the same thing
> using for_each and boost::lambda, so I tried
> this approach:
>
> long c = 0;
> for_each( v.begin(),
> v.end(),
> ( var( m( c / m.w, c % m.w ) ) = _1,
> ++var( c )
> )
> );
>
> This also fills MyMatrix, but with different values than the for loop.
> Which seems surprising to me.
> As far as I can tell, these two approaches should be equivalent, but
> apparently they're not. Anyone
> care to explain to me why?
>
> P.S. Sorry for the unfinished post which got through. Please ignore that
> one.
>
> --
> Alex Borghgraef
That's not going to work because the operator() call in the loop (i.e.
m(...)) is evaluated when the lambda expression is created, not each
time the lambda expression is evaluated.
Try replacing
var( m( c / m.w, c % m.w ) )
with
bind(&MyMatrix::operator(), var(m), var(c) / m->*&MyMatrix::w, var(c)
% m->*&MyMatrix::w)
This makes all accesses to m & c lazy (I think), so should update m as you want.
Stuart Dootson
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