accumulate usage

#include accumulate defined in two acts, is a cumulative sum, and the other is a custom type of data processing

1. cumulative sum

int sum = accumulate(vec.begin() , vec.end() , 42);  

parameter accumulate with three: the first two parameters of the specified range of elements to be accumulated, and the third parameter is the initial value of accumulation.

Its function will accumulate a specified internal variable is set to an initial value, then the accumulated values ​​for all elements in the input range on this initial value. accumulating the results of the algorithm returns accumulate, return type is its third argument type.

You may be used to accumulate string type vector connecting the container elements:

string sum = accumulate(v.begin() , v.end() , string(" "));  

The effect of this call is: start with an empty string, the vec in each element into a string.

2. The process of custom data types

C ++ in the STL type have a common value calculation function - accumulate (), the array can be used to directly calculate container C ++ or built-in data types, such as:
?????
#include
int ARR [] = {10,20, 30,40 , 50};
Vector VA (& ARR [0], & ARR [. 5]);
int the accumulate = SUM (va.begin (), va.end (), 0); // SUM = 150
?????
but for custom data type, we need to write himself a callback function to implement custom data processing, and then let the fourth parameter as accumulate (), and accumulate () prototype is

template<class _InIt, class _Ty,  class _Fn2> 
inline _Ty _Accumulate(_InIt _First, _InIt _Last, _Ty _Val, _Fn2 _Func)  
{   // return sum of _Val and all in [_First, _Last), using _Func  
    for (; _First != _Last; ++_First)  
        _Val = _Func(_Val, *_First);  
    return (_Val);  
}  

For example:

#include <vector>  
#include <string>  
using namespace std;  
  
struct Grade  
{  
    string name;  
    int grade;  
};  
  
int main()  
{  
    Grade subject[3] = {  
        { "English", 80 },  
        { "Biology", 70 },  
        { "History", 90 }  
    };  
  
    int sum = accumulate(subject, subject + 3, 0, [](int a, Grade b){return a + b.grade; });  
    cout << sum << endl;  
  
    system("pause");  
    return 0;  
}  
Da
Published 37 original articles · won praise 3 · Views 1077

Guess you like

Origin blog.csdn.net/weixin_43264873/article/details/103338593