Skip to content

Instantly share code, notes, and snippets.

@lufehr
Created September 12, 2012 22:55
Show Gist options
  • Save lufehr/3710585 to your computer and use it in GitHub Desktop.
Save lufehr/3710585 to your computer and use it in GitHub Desktop.
Blog - C++ STL Algorithm accumulate()
// addition
template <class InputIterator, class T>
T accumulate (InputIterator first, InputIterator last, T init)
{
while (first!=last) init = init + *first++;
return init;
}
// general Operation
template <class InputIterator, class T, Class binaryOperation>
T accumulate (InputIterator first, InputIterator last, T init, binaryOperation)
{
while (first!=last) init = op(init, *first++);
return init;
}
#include <numeric>    // for accumulate
#include <vector>         // for vector
#include <functional>     // for multiplies
#include <iostream>   // for cout
int main()
{
std::vector<int> v;
v.push_back(3);
v.push_back(2);
v.push_back(4);
// addition
int sum = accumulate(v.begin(), v.end(), 0);
std::cout << "Summe: " << sum << std::endl; // Ausgabe => Summe: 9
// Operation -> std::multiplies<int>()
int prod = accumulate(v.begin(), v.end(), 1, std::multiplies<int>());
std::cout << "Produkt: " << prod << std::endl; // Ausgabe => Produkt: 24
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment