Boost Users :
Subject: Re: [Boost-users] BOOST_FOREACH with Index
From: The Dude (thedsadude_at_[hidden])
Date: 2009-12-13 17:18:25
On Sun, Dec 13, 2009 at 11:51 PM, Eric Niebler <eric_at_[hidden]> wrote:
> The Dude wrote:
>> Boost::foreach is very useful for iterating over a sequence and doing
>> something that depends only on the iterated element, e.g.,
>> BOOST_FOREACH(const Foo &f, foos)
>> cout << f.bar() << endl;
>> 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
>> BOOST_FOREACH(size_t i, const Foo &f, foos)
>> cout << "The bar of element " << i << " is " << f.bar() << endl;
>> Is there an easy way to do so?
> Why not:
> int index = 0;
> BOOST_FOREACH(const Foo &f, foos)
> // ... stuff ...
> Eric Niebler
> BoostPro Computing
> Boost-users mailing list
Thanks for you answer. I'm not sure how to answer the "why not"? The code
you write certainly will work, but so would the predecessor to BOOST_FOREACH
in the first place, no? So here's my attempt:
1. For shorter loops, this changes 2 LOCs to 5.
2. For longer loops, the iteration code changes its meaning if it appears
before the ++index or after.
3. The variable index has scope outside the loop.
4. Other people think so, e.g., the author's of D language
It's true that none of these points is really a proof. Still, I'd be
really happy to hack my own INDEX_FOREACH, but the 500+ LOCs of
BOOST_FOREACH left me daunted.
Thanks & Bye,
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