[Home]  [Edit this page]  [Recent Changes]  [Special Pages]  [Help
CppAccumulate

(C++) std::accumulate

Function to summarize a range. Comparable to std::for_each (as mentioned by Meyers, 'Effective STL', item 37).

  1. include <vector>
  2. include <numeric>
  3. include <cassert>
int main() { std::vector<double> data(100,1.0); //Fill vector with 100 1.0's const double mySum = std::accumulate( data.begin(), data.end(), 0.0); assert(mySum == 100.0); }


You can also use std::accumulate using a functor. The example shows how to calculate the product of all elements of a std::vector using the STL functor std::multiplies:

  1. include <vector>
  2. include <numeric>
  3. include <cassert>
int main() { std::vector<int> v; v.push_back(1); v.push_back(2); v.push_back(3); v.push_back(4); assert(std::accumulate(v.begin(),v.end(),1,std::multiplies<int>())==24); }


A custom functor

This functor calculates the denominator of the Gibbs or Boltzmann distribution

            exp( q(a) / tau )
p(a) = ----------------------------
            SUM( exp( q(a) / tau) )
p(a): chance of selecting action a
exp: natural exponent
q(a): estimated value of action a 
tau: temperature


  1. include <numeric>
  2. include <vector>
  3. include <cassert>
  4. include <math>
template <class T> struct GibbsFunctor : public std::binary_function<T, T, T> { GibbsFunctor(const double& tau) : mTau(tau) {} T operator() (const T& sum, const T& x) const { return sum + std::exp( x / mTau ); } const double mTau; }; int main() { std::vector<double> v; v.push_back(0.1); v.push_back(0.2); v.push_back(0.3); const double sumGibbs = std::accumulate(v.begin(),v.end(),0.0,GibbsFunctor<double>(1.0)); }


std::accumulate's definition

From the numeric header file supplied with C++ Builder 6:

// Copyright (c) 1994
// Hewlett-Packard Company
template <class InputIterator, class T>
T accumulate (InputIterator first, InputIterator last, T init)
{
  while (first != last) init = init + *first++; 
  return init;
}
template <class InputIterator, class T, class BinaryOperation>
T accumulate (InputIterator first, InputIterator last, T init,
              BinaryOperation binary_op)
{
  while (first != last) init = binary_op(init, *first++); 
  return init;
}


Code links



last edited (November 9, 2006) by bilderbikkel, Number of views: 3004, Current Rev: 7 (Diff)

[Edit this page]  [Page history]  [What links here]  [Discuss this topic]  [Printer Friendly]  

Members

Username:

Password:


Register
Forgot Password?




Programmers Heaven - for .NET, Java, C/C++ and WEB Developers!
© 1996-2008 Community Networks Ltd. All rights reserved. Reproduction in whole or in part, in any form or medium without express written permission is prohibited. Violators of this policy may be subject to legal action. Please read Terms Of Use and Privacy Statement for more information. Development by Tore Nestenius at .NET Consultant - Synchron Data.