## accumulate

Interval algorithm accumulate supports custom calculate method to count elemeints in the special range.
We can use it to get summary, multiple, average and etc of some elements, it’s very convenient and powerful. The syntax and usage example are in the following.

Syntax:

``````template< class InputIt, class T >
T accumulate( InputIt first, InputIt last, T init );

template< class InputIt, class T, class BinaryOperation >
T accumulate( InputIt first, InputIt last, T init, BinaryOperation op );
``````

Example:

``````#include <vector>
#include <algorithm>
#include <iostream>
#include <numeric>
using namespace std;

int main(int argc, char *argv[])
{
vector<int> vec;
for( int i = 1; i < 11; ++i )
{
vec.push_back( i );
}
string result = accumulate( next( vec.begin() ), vec.end(), to_string( vec[0] ),
[](string s1, int value){ return s1 + " - " + to_string( value ); } );
cout << "result: " << result << endl;
return 0;
}
/*
result: 1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9 - 10
*/
``````

## for_each

The algorithm for_each visits every element in the container and run our function.
Here is its possible implementation.

``````template<class InputIt, class UnaryFunction>
constexpr UnaryFunction for_each(InputIt first, InputIt last, UnaryFunction f)
{
for (; first != last; ++first) {
f(*first);
}
return f;
}
``````

Usage example:

``````#include <vector>
#include <algorithm>
#include <iostream>
#include <numeric>
using namespace std;

class Sum
{
public:
Sum(){ result = 0; }
void operator()( int value ){ result = result + value; }
int result;
};

int main(int argc, char *argv[])
{
vector<int> vec;
for( int i = 1; i < 11; ++i )
{
vec.push_back( i );
}
for_each( vec.begin(), vec.end(), [](int element){ cout << element << "\t"; } );
cout << endl;

Sum func = for_each( vec.begin(), vec.end(), Sum() );
cout << "result: " << func.result << endl;
return 0;
}
/*
1 2 3 4 5 6 7 8 9 10
result: 55
*/
``````
Categories: AlgorithmCPlusPlus

Article Rating
Subscribe
Notify of