c++boostiteratorboost-foreach

How can I iterate over two vectors simultaneously using BOOST_FOREACH?


I'd like to replicate the following with BOOST FOREACH

std::vector<int>::const_iterator i1;
std::vector<int>::const_iterator i2;
for( i1 = v1.begin(), i2 = v2.begin();
     i1 < v1.end() && i2 < v2.end();
     ++i1, ++i2 )
{
     doSomething( *i1, *i2 );
}

Solution

  • Iterating over two things simultaneously is called a "zip" (from functional programming), and Boost has a zip iterator:

    The zip iterator provides the ability to parallel-iterate over several controlled sequences simultaneously. A zip iterator is constructed from a tuple of iterators. Moving the zip iterator moves all the iterators in parallel. Dereferencing the zip iterator returns a tuple that contains the results of dereferencing the individual iterators.

    Note that it's an iterator, not a range, so to use BOOST_FOREACH you're going to have to stuff two of them into an iterator_range or pair. So it won't be pretty, but with a bit of care you can probably come up with a simple zip_range and write:

    BOOST_FOREACH(boost::tuple<int,int> &p, zip_range(v1, v2)) {
        doSomething(p.get<0>(), p.get<1>());
    }
    

    Or special-case for 2 and use std::pair rather than boost::tuple.

    I suppose that since doSomething might have parameters (int&, int&), actually we want a tuple<int&,int&>. Hope it works.