C++ STL 算法库学习之adjacent_difference,count,partial_sum,accumulate,count_if详解

1.连续计算类

adjacent_difference,count,partial_sum,accumulate,count_if 均是以线性复杂度

accumulate
#include <numeric>
TYPE accumulate( iterator start, iterator end, TYPE val );
TYPE accumulate( iterator start, iterator end, TYPE val, BinaryFunction f );

The accummulate() function computes the sum of val and all of the elements in the range[start,end).

If the binary function f if specified, it is used instead of the + operator to perform thesummation

#include "stdafx.h"
#include <iostream>
#include <functional>
#include <numeric>
#include <vector>


#if  0
int main()
{
    using namespace std;
    vector<int>v1, v2(20);
    vector<int>::iterator iter1, iter2;

    for (auto i = 1; i < 21; i++)
    {
        v1.push_back(i);
    }

    cout << "V1:" << endl;
    for (auto i = 0; i < 20; i++)
    {
        cout << v1[i] << " ";
    }
    cout << endl;

    auto total = accumulate(v1.begin(), v1.end(), 0);
    cout << "0 begin:"<<total << endl;
    total = accumulate(v1.begin(), v1.end(), 10);
    cout << "10 begin"<<total << endl;

    int j = 0;
    int partotal;
    for (iter1 = v1.begin(); iter1 != v1.end(); iter1++)
    {
        partotal = accumulate(v1.begin(), iter1 + 1, 0);
        v2[j] = partotal;
        j++;
    }

    cout << "partotal:" << partotal << endl;
    cout << "The vector of partial sums is:\n ( ";
    for (iter2 = v2.begin(); iter2 != v2.end(); iter2++)
        cout << *iter2 << 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值