[Home]
[Edit this page]
[Recent Changes]
[Special Pages]
[Help]
CppAccumulate
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:
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
CppAccumulate
(C++) std::accumulate
Function to summarize a range. Comparable to std::for_each (as mentioned by Meyers, 'Effective STL', item 37).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); }
- include <vector>
- include <numeric>
- include <cassert>
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:
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); }
- include <vector>
- include <numeric>
- include <cassert>
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
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)); }
- include <numeric>
- include <vector>
- include <cassert>
- include <math>
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
- #include
- assert
- cassert (header file)
- const
- double
- #include
- int
- numeric (header file)
- return
- std
- template
- std::vector
- vector
- vector (header file)
- while
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
