accumulate

C++ STL中有一个通用的数值类型计算函数— accumulate(),可以用来直接计算数组或者容器中C++内置数据类型,例如:

#include < numeric >
int arr[] = { 10 , 20 , 30 , 40 , 50 };
vector
< int > va( & arr[ 0 ], & arr[ 5 ]);
int sum = accumulate(va.begin(),va.end(), 0 );  // sum = 150,默认操作是"累加"
   
   
   
   
 
实例一:
#include <iostream>
#include <numeric>
using namespace std;

int main() 
{
    int x[] = {1,2,3,4,5};

    // 1 * 2 * 3 * 4 * 5 and * 1
    int sum = accumulate(x, x+5, 1, multiplies<int>());
    cout << "sum = " << sum << endl;

    // 1 * 2 * 3 * 4 * 5 and * 2
    sum = accumulate(x, x+5, 2, multiplies<int>());
    cout << "sum = " << sum << endl;

    // 2 * 3 * 4 and * 10
    sum = accumulate(x+2, x+4, 10, multiplies<int>());
    cout << "sum = " << sum << endl;

	system("pause");
    return 0;
}

/*
Output:

sum = 120
sum = 240
sum = 120
请按任意键继续. . .
*/

 
实例二:
#include <iostream>
#include <numeric>
#include <vector>
#include <string>
using namespace std;

struct Student
{
       string name;
       int total;
};

class PS{
 public:
        int operator()(int t1,const Student& t2)
        {
            return (t1 + t2.total);
        }        
};

int main()
{
    Student student[3]={
            {"hicjiajia",10},
            {"sijikaoshi",20},
            {"what",40}
            };
    
    int sum=accumulate(&student[0],&student[3],0,PS());
    cout<<"sum = "<<sum<<endl;

    system("pause");
    return 0;
}

/*
Output:

sum = 70
请按任意键继续. . .
*/

你可能感兴趣的:(accumulate)