Created
September 12, 2012 22:55
-
-
Save lufehr/3710585 to your computer and use it in GitHub Desktop.
Blog - C++ STL Algorithm accumulate()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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