Boost logo

Boost :

Subject: Re: [boost] [General] A standard idiom or technique?
From: mbiddeg_at_[hidden]
Date: 2008-10-24 04:56:56


Robert Jones wrote:

>A recent post in this list started me thinking...
>
>Given this code snippet,
>
>using namespace std;
>
>void f( int, int );
>
>vector<int> v1;
>vector<int> v2;
>
>// populate...
>
>for ( unsigned i = 0; i <= v1.size( ); ++ i )
>{
> f( v1[ i ], v2[ i ] );
>}
>
>How would you write this as a for_each() or in some other Boosty,
>functional
>way?
>(The aspect I'm trying to highlight is that two iterators over different
>ranges must
>advance in step)
>
>One could imagine a tuple-based solution, in which one specifies how an
>operation
>applied to the tuple distributes to operations applied to each of the
>tuple's elements.
>
>Does any such thing exist in Boost? Is it ever necessary, or can the
>functionality be
>achieved by some C++/STL/Boost idiom that I've not thought of?
>
>If there is no obvious technique, is there any interest in a Boost
>library
>which address
>this in a generic way?
>
>Thanks.
>
>- Rob.

The tuple-based solution seems elegant if you have a varying number of ranges.
For your two ranges requirement, a simple custom writing of a for_each would do, like this:

template<class ForwardIterator, class ForwardIterator2, Class Op>
Op for_each(ForwardIterator first, ForwardIterator last, ForwardIterator2 first2, Op op){

        for(;first != last; ++first, ++first2)
                op(*(first), *(first2));

        return (op);

}

Does this work for you?


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk