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
请按任意键继续. . .
*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值