Boost logo

Boost Users :

Subject: [Boost-users] Clever simultaneous iteration over multiple containers
From: Joseph Wakeling (joseph.wakeling_at_[hidden])
Date: 2010-03-13 18:09:12


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.

Can anyone advise?

Thanks & best wishes,

    -- Joe


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