C++--accumulate介绍

在C++中,accumulate是一个用于对容器中的元素进行累加操作的函数模板,位于 头文件中。它允许你对容器(如vector或array)中的元素进行累加运算,并返回累加的结果。

源代码展示

cpp 复制代码
template<class InputIterator, class Type>  
Type accumulate(  
InputIterator _First,  //开始迭代器  
InputIterator _Last,   //结束迭代器  
Type _Val              //初始值  
);

源码剖析

cpp 复制代码
template<class InputIterator, class T> 
T accumulate( 
InputIterator first,  
InputIterator last,   
T init ) 
{
    for(;first != last; ++first) 
        init = init + *first; //默认为累加 
    return init; 
}

应用举例

cpp 复制代码
 #include <iostream> 
    #include <vector> 
    #include <numeric> 
    using namespace std; 
    int main() 
    {
        vector<int>v{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; 
        auto sum = accumulate(v.begin(), v.end(), 0);//把v的所有值累加,初始值为0

    
        cout << "累加结果为:"<<sum<<endl; 
    
        return 0; 
    }

本篇完!

相关推荐
感哥3 小时前
C++ 多态
c++
沐怡旸10 小时前
【底层机制】std::string 解决的痛点?是什么?怎么实现的?怎么正确用?
c++·面试
River41613 小时前
Javer 学 c++(十三):引用篇
c++·后端
感哥15 小时前
C++ std::set
c++
侃侃_天下16 小时前
最终的信号类
开发语言·c++·算法
博笙困了16 小时前
AcWing学习——差分
c++·算法
echoarts16 小时前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
Aomnitrix17 小时前
知识管理新范式——cpolar+Wiki.js打造企业级分布式知识库
开发语言·javascript·分布式
青草地溪水旁17 小时前
设计模式(C++)详解—抽象工厂模式 (Abstract Factory)(2)
c++·设计模式·抽象工厂模式
青草地溪水旁17 小时前
设计模式(C++)详解—抽象工厂模式 (Abstract Factory)(1)
c++·设计模式·抽象工厂模式