<div dir="ltr"><br><br><div class="gmail_quote">On Sun, Dec 13, 2009 at 11:51 PM, Eric Niebler <span dir="ltr">&lt;<a href="mailto:eric@boostpro.com">eric@boostpro.com</a>&gt;</span> wrote:<br><blockquote class="gmail_quote" style="border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt 0.8ex; padding-left: 1ex;">
<div><div></div><div class="h5">The Dude wrote:<br>
<blockquote class="gmail_quote" style="border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt 0.8ex; padding-left: 1ex;">
  Hello,<br>
<br>
  Boost::foreach is very useful for iterating over a sequence and doing something that depends only on the iterated element, e.g.,<br>
&lt;code&gt;<br>
BOOST_FOREACH(const Foo &amp;f, foos)<br>
  cout &lt;&lt; f.bar() &lt;&lt; endl;<br>
&lt;/code&gt;<br>
<br>
  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<br>
&lt;code&gt;<br>
BOOST_FOREACH(size_t i, const Foo &amp;f, foos)<br>
  cout &lt;&lt; &quot;The bar of element &quot; &lt;&lt; i &lt;&lt; &quot; is &quot; &lt;&lt; f.bar() &lt;&lt; endl;<br>
&lt;/code&gt;<br>
<br>
  Is there an easy way to do so?<br>
</blockquote>
<br>
<br></div></div>
Why not:<br>
<br>
  int index = 0;<div class="im"><br>
  BOOST_FOREACH(const Foo &amp;f, foos)<br></div>
  {<br>
    // ... stuff ...<br>
    ++index;<br>
  }<br>
<br>
?<br><font color="#888888">
<br>
-- <br>
Eric Niebler<br>
BoostPro Computing<br>
<a href="http://www.boostpro.com" target="_blank">http://www.boostpro.com</a></font><div><div></div><div class="h5"><br>
_______________________________________________<br>
Boost-users mailing list<br>
<a href="mailto:Boost-users@lists.boost.org" target="_blank">Boost-users@lists.boost.org</a><br>
<a href="http://listarchives.boost.org/mailman/listinfo.cgi/boost-users" target="_blank">http://listarchives.boost.org/mailman/listinfo.cgi/boost-users</a><br>
</div></div></blockquote></div><br><br>  Hello,<br><br>  Thanks for you answer. I&#39;m not sure how to answer the &quot;why not&quot;? The code you write certainly will work, but so would the predecessor to BOOST_FOREACH in the first place, no? So here&#39;s my attempt:<br>
1. For shorter loops, this changes 2 LOCs to 5.<br>2. For longer loops, the iteration code changes its meaning if it appears before the ++index or after.<br>3. The variable index has scope outside the loop.<br>4. Other people think so, e.g., the author&#39;s of D language <a href="http://en.wikipedia.org/wiki/D_(programming_language)#Example_1">http://en.wikipedia.org/wiki/D_(programming_language)#Example_1</a><br>
  It&#39;s true that none of these points is really a proof. Still, I&#39;d be really happy to hack my own INDEX_FOREACH, but the 500+ LOCs of BOOST_FOREACH left me daunted.<br><br>  Thanks &amp; Bye,<br><br>  TD<br>  <br>
</div>

