Boost logo

Boost Users :

Subject: Re: [Boost-users] Clever simultaneous iteration over multiple containers
From: Steven Watanabe (watanabesj_at_[hidden])
Date: 2010-03-13 18:43:55


AMDG

Joseph Wakeling wrote:
> Dear Boost users,
>
> A (possibly naïve) question, as I'm a reasonably competent C programmer
> but only a relative novice with C++, and just starting to get used to
> concepts from libraries like Boost.
>
> The BOOST_FOREACH macro provides a nice way to iterate over all the
> contents of a container like a vector, list, etc. But what about when
> several containers are involved?
>
> I'll give a concrete-ish example from a problem I'm working on. I have
> two vectors, vector<myClass *> v1 and vector<double> v2 where myClass is
> a base class and v1.size()==v2.size(). Then, what I want to do is,
>
> for(unsigned int i=0;i<v1.size();++i)
> v1.at(i)->func(v2.at(i));
>
> That works, of course; I'm just wondering if there is a more elegant or
> compiler-friendly way of writing this along the lines of the
> BOOST_FOREACH macro. Initialising separate iterators for both v1 and v2
> seems ugly/lots of boilerplate. I have seen the solution here:
> http://permalink.gmane.org/gmane.comp.lib.boost.user/31954
>
> ... but that seems less desirable because it involves using an extra
> library which I don't think is standard in Linux distros.
>
> I have the impression that the zip_iterator boost lib is useful here,
> but did not fully understand if or how.
>

To use zip_iterator, you would need something like
std::make_pair(boost::make_zip_iterator(boost::make_tuple(v1.begin(),
v2.begin())), boost::make_zip_iterator(boost::make_tuple(v1.end(),
v2.end())));

The RangeEx library which has been accepted, but is not
yet in the trunk, also provides a zip operation that works
with ranges instead of iterators.

In Christ,
Steven Watanabe


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