Boost logo

Boost Users :

Subject: Re: [Boost-users] BOOST_FOREACH with Index
From: Eric Niebler (eric_at_[hidden])
Date: 2009-12-13 16:51:47


The Dude wrote:
> Hello,
>
> Boost::foreach is very useful for iterating over a sequence and doing
> something that depends only on the iterated element, e.g.,
> <code>
> BOOST_FOREACH(const Foo &f, foos)
> cout << f.bar() << endl;
> </code>
>
> However, I often need to iterate over a sequence and do some operation
> that depends on both the iterated element and the iteration index. E.g.,
> I would like something like
> <code>
> BOOST_FOREACH(size_t i, const Foo &f, foos)
> cout << "The bar of element " << i << " is " << f.bar() << endl;
> </code>
>
> Is there an easy way to do so?

Why not:

   int index = 0;
   BOOST_FOREACH(const Foo &f, foos)
   {
     // ... stuff ...
     ++index;
   }

?

-- 
Eric Niebler
BoostPro Computing
http://www.boostpro.com

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