当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


C++ std::accumulate()用法及代码示例

C++ STL 支持多种函数和模板,以不同的方式解决问题。

C++ STL std::accumulate() 函数

std::accumulate() 函数用于累加所有的值range [first, last]包括任何变量initial_sum

累积函数 do 的默认操作是将所有元素相加,但可以执行不同的操作。

accumulate() 函数的语法:

    accumulate(start, end, initial_sum);

这里,

  • start:是迭代器的初始位置
  • end: 是迭代器的最后一个位置。

注意:还可以在累加函数中传递一个附加参数,该参数指定要执行的操作类型。

带有附加参数的 accumulate() 函数的语法:

    accumulate(start, end, initial_sum, func);

这里,func是要执行的附加操作。

C++程序演示std::accumulate()函数的例子

#include <bits/stdc++.h>
#include <vector>
using namespace std;

int main()
{
    // Initialization of vector
    vector<int> vec{1,2,3,4,5,6,7,8,9};

    // Taking initial sum as 0
    int sum = 0;
    cout << "\n Initial value of sum = " << sum << endl;

    // Demonstration of accumulate function
    // to sum all the elements of the vector
    sum = accumulate(vec.begin(), vec.end(), sum);

    cout << " Value of sum after accumulate = " << sum << endl;

    // Changing value of initial_sum to 50
    sum = 50;

    cout << "\n Initial value of sum = " << sum << endl;

    // Demonstration of accumulate function
    // with the additional argument
    // Here additional argument is used to
    // subtract all the elements from the
    // initial sum. Additional argument can be
    // any valid function or operation
    sum = accumulate(vec.begin(), vec.end(), sum, minus<int>());

    cout << " Value of sum after accumulate function with optional argument = " << sum << endl;

    return 0;
}

输出

 Initial value of sum = 0
 Value of sum after accumulate = 45

 Initial value of sum = 50
 Value of sum after accumulate function with optional argument = 5


相关用法


注:本文由纯净天空筛选整理自 std::accumulate() function with example in C++ STL。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。