<p>I have a 'foreach' macro I use frequently in C++ that works for most STL containers:</p>

<pre><code>#define foreach(var, container) \
  for(typeof((container).begin()) var = (container).begin(); \
      var != (container).end(); \
      ++var)
</code></pre>

<p>(Note that 'typeof' is a gcc extension.) It is used like this:</p>

<pre><code>std::vector&lt; Blorgus &gt; blorgi = ...;
foreach(blorgus, blorgi) {
  blorgus-&gt;draw();
}
</code></pre>

<p>I would like to make something similar that iterates over a map's values. Call it "foreach_value", perhaps. So instead of writing</p>

<pre><code>foreach(pair, mymap) {
  pair-&gt;second-&gt;foo();
}
</code></pre>

<p>I would write</p>

<pre><code>foreach_value(v, mymap) {
  v.foo();
}
</code></pre>

<p>I can't come up with a macro that will do this, because it requires declaring two variables: the iterator and the value variable ('v', above). I don't know how to do that in the initializer of a for loop, even using gcc extensions. I could declare it just before the foreach_value call, but then it will conflict with other instances of the foreach_value macro in the same scope. If I could suffix the current line number to the iterator variable name, it would work, but I don't know how to do that.</p>

[{'answer_id': 78754, 'author': 'Tyler', 'author_id': 3561, 'author_profile': 'https://Stackoverflow.com/users/3561', 'pm_score': 0, 'selected': False, 'text': '<p>You could define a template class that takes the type of mymap as a template parameter, and acts like an iterator over the values by overloading * and ->.</p>\n'}, {'answer_id': 78780, 'author': 'Tom Leys', 'author_id': 11440, 'author_profile': 'https://Stackoverflow.com/users/11440', 'pm_score': 3, 'selected': False, 'text': '<p>You would be looking for <a href="http://www.boost.org/doc/libs/1_36_0/doc/html/foreach.html" rel="nofollow noreferrer">BOOST_FOREACH</a> - they have done all the work for you already!</p>\n\n<p>If you do want to roll your own, you can declare a block anywhere in C++, which resolves your scope issue with your intermediate storage of itr->second\n...</p>\n\n<pre><code>// Valid C++ code (which does nothing useful)\n{\n  int a = 21; // Which could be storage of your value type\n}\n// a out of scope here\n{ \n  int a = 32; // Does not conflict with a above\n}\n</code></pre>\n'}, {'answer_id': 78793, 'author': 'porges', 'author_id': 10311, 'author_profile': 'https://Stackoverflow.com/users/10311', 'pm_score': 1, 'selected': False, 'text': '<p>Have you thought of using the <a href="http://www.boost.org/" rel="nofollow noreferrer">Boost libraries</a>? They have a <a href="http://www.boost.org/doc/libs/1_36_0/doc/html/foreach.html" rel="nofollow noreferrer"><code>foreach</code> macro implemented</a> which is probably more robust than anything you\'ll write... and there is also <a href="http://www.boost.org/doc/libs/1_36_0/libs/iterator/doc/transform_iterator.html" rel="nofollow noreferrer"><code>transform_iterator</code></a> which would seem to be able to be used to do the second-extraction part of what you want.</p>\n\n<p>Unfortunately I can\'t tell you exactly <em>how</em> to use it because I don\'t know enough C++ :) <a href="http://www.google.com/search?q=boost+foreach+transform_iterator" rel="nofollow noreferrer">This Google search</a> turns up some promising answers: <a href="http://groups.google.com/group/comp.lang.c++.moderated/msg/26b344960588d3ac" rel="nofollow noreferrer">comp.lang.c++.moderated</a>, <a href="https://network-geographics.com/weblog/2008/06/boost_transform_iterator_use_cas.html" rel="nofollow noreferrer">Boost transform_iterator use case</a>.</p>\n'}, {'answer_id': 79071, 'author': 'archbishop', 'author_id': 14529, 'author_profile': 'https://Stackoverflow.com/users/14529', 'pm_score': 4, 'selected': True, 'text': "<p>You can do this using two loops.  The first declares the iterator, with a name which is a function of the container variable (and you can make this uglier if you're worried about conflicts with your own code).  The second declares the value variable.</p>\n\n<pre><code>#define ci(container) container ## iter\n#define foreach_value(var, container) \\\n    for (typeof((container).begin()) ci(container) = container.begin(); \\\n         ci(container) != container.end(); ) \\\n        for (typeof(ci(container)-&gt;second)* var = &amp;ci(container)-&gt;second; \\\n             ci(container) != container.end(); \\\n             (++ci(container) != container.end()) ? \\\n                 (var = &amp;ci(container)-&gt;second) : var)\n</code></pre>\n\n<p>By using the same loop termination condition, the outer loop only happens once (and if you're lucky, gets optimized away).  Also, you avoid calling ->second on the iterator if the map is empty.  That's the same reason for the ternary operator in the increment of the inner loop; at the end, we just leave var at the last value, since it won't be referenced again.</p>\n\n<p>You could inline ci(container), but I think it makes the macro more readable.</p>\n"}, {'answer_id': 79250, 'author': 'Zachary Garrett', 'author_id': 14692, 'author_profile': 'https://Stackoverflow.com/users/14692', 'pm_score': 2, 'selected': False, 'text': '<p>The STL <em><a href="http://www.sgi.com/tech/stl/transform.html" rel="nofollow noreferrer">transform</a></em> function also does something similar. </p>\n\n<p>The arguments are (in order):</p>\n\n<ol>\n<li>An input iterator designating the beginning of a container </li>\n<li>An input iterator designating the end of the container</li>\n<li>An output iterator defining where to put the output (for an in-place transform, similar to for-each, just pass the the input iterator in #1)</li>\n<li>A unary function (function object) to perform on each element</li>\n</ol>\n\n<p>For a very simple example, you could capitalize each character in a string by:</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;string&gt;\n#include &lt;algorithm&gt;\n#include &lt;cctype&gt;\n\nint main(int argc, char* argv[]) {\n    std::string s("my lowercase string");\n    std::transform(s.begin(), s.end(), s.begin(), toupper);\n    std::cout &lt;&lt; s &lt;&lt; std::endl; // "MY LOWERCASE STRING"\n}\n</code></pre>\n\n<p>Alternatively there is also the <em><a href="http://www.sgi.com/tech/stl/accumulate.html" rel="nofollow noreferrer">accumulate</a></em> function, which allows some values to be retained between calls to the function object. <em>accumulate</em> does not modify the data in the input container as is the case with <em>transform</em>.</p>\n'}, {'answer_id': 79463, 'author': 'Mark Kegel', 'author_id': 14788, 'author_profile': 'https://Stackoverflow.com/users/14788', 'pm_score': 1, 'selected': False, 'text': '<p>Boost::For_each is by far your best bet. The nifty thing is that what they actually give you is the macro BOOST_FOREACH() which you can then wrap and #define to whatever you would really like to call it in your code. Most everyone will opt for the good old "foreach", but other shops may have different coding standards, so this fits with that mindset. Boost also has lots of other goodies for C++ developers! Well worth using.</p>\n'}, {'answer_id': 80671, 'author': 'Assaf Lavie', 'author_id': 11208, 'author_profile': 'https://Stackoverflow.com/users/11208', 'pm_score': 0, 'selected': False, 'text': "<pre><code>#define foreach(var, container) for (typeof((container).begin()) var = (container).begin(); var != (container).end(); ++var)\n</code></pre>\n\n<p>There's no typeof in C++... how is this compiling for you? (it's certainly not portable)</p>\n"}, {'answer_id': 4214768, 'author': 'Artur Sowiński', 'author_id': 512072, 'author_profile': 'https://Stackoverflow.com/users/512072', 'pm_score': 1, 'selected': False, 'text': '<p>I created a little Foreach.h helper with a few variants of foreach() including both ones operating on the local variables and on pointers, with also an extra version secured against deleting elements from within loop. So the code that uses my macros looks nice and cozy like this:</p>\n\n<pre><code>#include &lt;cstdio&gt;\n#include &lt;vector&gt;\n#include "foreach.h"\n\nint main()\n{\n    // make int vector and fill it\n    vector&lt;int&gt; k;\n    for (int i=0; i&lt;10; ++i) k.push_back(i);\n\n    // show what the upper loop filled\n    foreach_ (it, k) printf("%i ",(*it));\n    printf("\\n");\n\n    // show all of the data, but get rid of 4\n    // http://en.wikipedia.org/wiki/Tetraphobia :)\n    foreachdel_ (it, k)\n    {\n        if (*it == 4) it=k.erase(it);\n        printf("%i ",(*it));\n    }\n    printf("\\n");\n\n    return 0;\n}\n</code></pre>\n\n<p>output:</p>\n\n<pre><code>0 1 2 3 4 5 6 7 8 9\n0 1 2 3 5 6 7 8 9\n</code></pre>\n\n<p>My <a href="http://pleasanthacking.com/2010/06/17/foreach-in-cpp/" rel="nofollow" title="Foreach in c++">Foreach.h</a> provides following macros:</p>\n\n<ul>\n<li>foreach() - regular foreach for pointers </li>\n<li>foreach_() - regular foreach for local variables </li>\n<li>foreachdel() - foreach version with checks for deletion within loop, pointer version</li>\n<li>foreachdel_() - foreach version with checks for deletion within loop, local variable version</li>\n</ul>\n\n<p>They sure do work for me, I hope they will also make your life a bit easier :)</p>\n'}, {'answer_id': 7253042, 'author': 'Stuart Berg', 'author_id': 162094, 'author_profile': 'https://Stackoverflow.com/users/162094', 'pm_score': 1, 'selected': False, 'text': '<p>There are two parts to this question.  You need to somehow (1) generate an iterator (or rather, an iterable sequence) over you map\'s <em>values</em> (not keys), and (2) use a macro to do the iteration without a lot of boilerplate.</p>\n\n<p>The cleanest solution is to use a <a href="http://www.boost.org/doc/libs/1_47_0/libs/range/doc/html/index.html" rel="nofollow">Boost Range</a> <a href="http://www.boost.org/doc/libs/1_47_0/libs/range/doc/html/range/reference/adaptors/introduction.html" rel="nofollow">Adaptor</a> for part (1) and <a href="http://www.boost.org/doc/libs/1_47_0/doc/html/foreach.html" rel="nofollow">Boost Foreach</a> for part (2).  You don\'t need to write the macro or implement the iterator yourself.</p>\n\n<pre><code>#include &lt;map&gt;\n#include &lt;string&gt;\n#include &lt;boost/range/adaptor/map.hpp&gt;\n#include &lt;boost/foreach.hpp&gt;\n\nint main()\n{\n    // Sample data\n    std::map&lt;int, std::string&gt; myMap ;\n    myMap[0] = "Zero" ;\n    myMap[10] = "Ten" ;\n    myMap[20] = "Twenty" ;\n\n    // Loop over map values\n    BOOST_FOREACH( std::string text, myMap | boost::adaptors::map_values )\n    {\n        std::cout &lt;&lt; text &lt;&lt; " " ;\n    }\n}\n// Output:\n// Zero Ten Twenty\n</code></pre>\n'}, {'answer_id': 11972376, 'author': 'marko.ristin', 'author_id': 1600678, 'author_profile': 'https://Stackoverflow.com/users/1600678', 'pm_score': 0, 'selected': False, 'text': '<p>I implemented my own <code>foreach_value</code> based on the <code>Boost</code> <code>foreach</code> code:</p>\n\n<pre><code>#include &lt;boost/preprocessor/cat.hpp&gt;\n#define MUNZEKONZA_FOREACH_IN_MAP_ID(x)  BOOST_PP_CAT(x, __LINE__)\n\nnamespace munzekonza {\nnamespace foreach_in_map_private {\ninline bool set_false(bool&amp; b) {\n  b = false;\n  return false;\n}\n\n}\n}\n\n#define MUNZEKONZA_FOREACH_VALUE(value, map)                                  \\\nfor(auto MUNZEKONZA_FOREACH_IN_MAP_ID(_foreach_in_map_it) = map.begin();      \\\n        MUNZEKONZA_FOREACH_IN_MAP_ID(_foreach_in_map_it) != map.end();)       \\\nfor(bool MUNZEKONZA_FOREACH_IN_MAP_ID(_foreach_in_map_continue) = true;       \\\n      MUNZEKONZA_FOREACH_IN_MAP_ID(_foreach_in_map_continue) &amp;&amp;               \\\n      MUNZEKONZA_FOREACH_IN_MAP_ID(_foreach_in_map_it) != map.end();          \\\n      (MUNZEKONZA_FOREACH_IN_MAP_ID(_foreach_in_map_continue)) ?              \\\n        ((void)++MUNZEKONZA_FOREACH_IN_MAP_ID(_foreach_in_map_it)) :          \\\n        (void)0)                                                              \\\n  if( munzekonza::foreach_in_map_private::set_false(                          \\\n          MUNZEKONZA_FOREACH_IN_MAP_ID(_foreach_in_map_continue))) {} else    \\\n  for( value = MUNZEKONZA_FOREACH_IN_MAP_ID(_foreach_in_map_it)-&gt;second;      \\\n        !MUNZEKONZA_FOREACH_IN_MAP_ID(_foreach_in_map_continue);              \\\n        MUNZEKONZA_FOREACH_IN_MAP_ID(_foreach_in_map_continue) = true)        \n</code></pre>\n\n<p>For example, you can use it in your code like this:</p>\n\n<pre><code>#define MUNZEKONZA_FOREACH_VALUE foreach_value\n\nstd::map&lt;int, std::string&gt; mymap;\n// populate the map ...\n\nforeach_value( const std::string&amp; value, mymap ) {\n  // do something with value\n}\n\n// change value\nforeach_value( std::string&amp; value, mymap ) {\n  value = "hey";\n}\n</code></pre>\n'}, {'answer_id': 41991034, 'author': 'Zoltán Horváth', 'author_id': 7503044, 'author_profile': 'https://Stackoverflow.com/users/7503044', 'pm_score': 0, 'selected': False, 'text': '<pre><code>#define zforeach(var, container) for(auto var = (container).begin(); var != (container).end(); ++var)\n</code></pre>\n\n<p>there is no typeof() so you can use this:</p>\n\n<pre><code>decltype((container).begin()) var \ndecltype(container)::iterator var\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/78717', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14528/']