Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><strong>Update 2:</strong> Boost.Lambda makes this a piece of cake:</p> <pre><code>// headers #include &lt;boost/lambda/lambda.hpp&gt; #include &lt;boost/lambda/bind.hpp&gt; using namespace boost::lambda; // ... cout &lt;&lt; accumulate(dv.begin(), dv.end(), 0, _1 += bind(&amp;strange::value, _2)) //strange defined below &lt;&lt; endl; </code></pre> <p><strong>Update:</strong> This has been bugging me for a while. I can't just get any of the STL algorithms to work in a decent manner. So, I rolled my own:</p> <pre><code>// include whatever ... using namespace std; // custom accumulator that computes a result of the // form: result += object.method(); // all other members same as that of std::accumulate template &lt;class I, class V, class Fn1, class Fn2&gt; V accumulate2(I first, I last, V val, Fn1 op, Fn2 memfn) { for (; first != last; ++first) val = op(val, memfn(*first)); return val; } struct strange { strange(int a, int b) : _a(a), _b(b) {} int value() { return _a + 10 * _b; } int _a, _b; }; int main() { std::vector&lt;strange&gt; dv; dv.push_back(strange(1, 3)); dv.push_back(strange(4, 6)); dv.push_back(strange(20, -11)); cout &lt;&lt; accumulate2(dv.begin(), dv.end(), 0, std::plus&lt;int&gt;(), mem_fun_ref(&amp;strange::value)) &lt;&lt; endl; } </code></pre> <p>Of course, the original solution still holds: The easiest is to implement an <code>operator+</code>. In this case:</p> <pre><code>double operator+(double v, Object const&amp; x) { return v + x.a_; } </code></pre> <p>and make it a friend of <code>Object</code> or member (look up why you may prefer one over the other):</p> <pre><code>class Object { //... friend double operator+(double v, Object const&amp; x); </code></pre> <p>and you're done with:</p> <pre><code> result = accumulate(collection.begin(), collection.end(), 0.0); </code></pre> <p>My earlier approach doesn't work because we need a <code>binary_function</code>.</p> <p><a href="http://www.sgi.com/tech/stl/accumulate.html" rel="nofollow noreferrer">std::accumulate</a> manual.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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