Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You wouldn't use <a href="http://www.cplusplus.com/reference/algorithm/for_each/" rel="nofollow noreferrer"><code>std::for_each</code></a>, but rather <a href="http://www.cplusplus.com/reference/algorithm/transform/" rel="nofollow noreferrer"><code>std::transform</code></a> (you're transforming a point into a single number.)</p> <p>For example:</p> <pre><code>#include &lt;algorithm&gt; // transform resides here #include &lt;iostream&gt; #include &lt;iterator&gt; #include &lt;vector&gt; struct Point { int x; int y; Point(int x, int y) : x(x), y(y) { } }; int point_to_int(const Point&amp; p) { return p.x; } int main() { std::vector&lt;Point&gt; points; points.push_back(Point(1, 2)); points.push_back(Point(4, 6)); std::vector&lt;int&gt; xs; std::transform(points.begin(), points.end(), std::back_inserter(xs), point_to_int); std::copy(xs.begin(), xs.end(), std::ostream_iterator&lt;int&gt;(std::cout, " ")); std::cout &lt;&lt; std::endl; return 0; } </code></pre> <p>Because you know the size of the container you'll be transforming, you might get a slight performance improvement from the following. I also find it more readable:</p> <pre><code>std::vector&lt;int&gt; xs; xs.reserve(points.size()); std::transform(points.begin(), points.end(), std::back_inserter(xs), point_to_int); </code></pre> <p>And with <a href="http://www.boost.org/doc/libs/1_40_0/doc/html/lambda.html" rel="nofollow noreferrer"><code>boost::lambda</code></a> along with <a href="http://www.boost.org/doc/libs/1_40_0/libs/bind/bind.html" rel="nofollow noreferrer"><code>boost::bind</code></a>:</p> <pre><code>#include &lt;algorithm&gt; #include &lt;iostream&gt; #include &lt;iterator&gt; #include &lt;vector&gt; #include &lt;boost/bind.hpp&gt; #include &lt;boost/lambda/lambda.hpp&gt; struct Point { int x; int y; Point(int x, int y) : x(x), y(y) { } }; int main() { using namespace boost; std::vector&lt;Point&gt; points; points.push_back(Point(1, 2)); points.push_back(Point(4, 6)); std::vector&lt;int&gt; xs; xs.reserve(points.size()); std::transform(points.begin(), points.end(), std::back_inserter(xs), bind(&amp;Point::x, lambda::_1)); std::copy(xs.begin(), xs.end(), std::ostream_iterator&lt;int&gt;(std::cout, " ")); std::cout &lt;&lt; std::endl; return 0; } </code></pre> <p>Removes the need to specify a function elsewhere. This keeps the code close to the calling site, and generally improves readability.</p> <p>In C++0x, it will simply be:</p> <pre><code>std::transform(points.begin(), points.end(), std::back_inserter(xs), [](const Point&amp; p){ return p.x; } ); </code></pre> <p>(To the best of my knowledge, anyway)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload