温馨提示×

c++中accumulate函数的用法是什么

c++
小亿
99
2024-02-19 14:31:24
栏目: 编程语言

在C++中,accumulate函数用于计算一个范围内的元素的累加值。其原型如下:

template< class InputIt, class T >
T accumulate( InputIt first, InputIt last, T init );

其中,firstlast表示一个迭代器范围,init是初始值。accumulate函数将从firstlast的所有元素相加,并返回累加值。

例如,可以这样使用accumulate函数:

#include <iostream>
#include <vector>
#include <numeric>

int main() {
    std::vector<int> vec = {1, 2, 3, 4, 5};

    int sum = std::accumulate(vec.begin(), vec.end(), 0);

    std::cout << "Sum of elements in vector: " << sum << std::endl;

    return 0;
}

以上代码将输出:

Sum of elements in vector: 15

0