前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【C++\408考研必备】模板函数、内存分配、标准模板

【C++\408考研必备】模板函数、内存分配、标准模板

作者头像
20岁爱吃必胜客
发布2022-11-13 10:00:10
2150
发布2022-11-13 10:00:10
举报
文章被收录于专栏:进步集

二维数组

char【7】【5】 char 合法形参: a【】【5】

char(*c)【5】; c= new char【n】【5】;

char **x

STL

accumulate用于计算init和[first , last)内部所有元素的总和。需要提供一个init,表示当[first,last)为空的区间仍然可以获取一个明确定义的数值,如果想获得[first,last)内所有数值的总和,应将init设为0 二元操作符不必满足交换律和结合律,是的accumulate的行为顺序有着明确的定义:先将init初始化,然后针对[first,last)区间内的每一个迭代器i,依次执行init = init + *i(第一版本) 或者 init = binary_op(init, *i) (第二版本)

代码语言:javascript
复制
//版本1
template <class InputIterator,class T>
T accumulate(InputIterator first,InputIterator last,T init){
    for(;first != last; ++first){
        init += *first; //将每个元素数值累加到init身上
    }
    return init;
}
 
//版本2
template <class InputIterator,class T,class BinaryOperation>
T accumulate(InputIterator first,InputIterator last,T init,
             BinaryOperation binary_op){
    for(;first!=last;++first){
        init = binary_op(init, *first);//对每一个元素执行二元操作
    }
    return init;
}
代码语言:javascript
复制
#include <iostream>   //std::cout
#include <functional> //std::minuc
#include <numeric>    //std::accumulate
 
int my_function(int x,int y){return x + 2*y;}
struct my_class{
    int operator()(int x,int y){
        return x + 3*y;
    }
}my_object;
 
int main(){
    int init = 100;
    int numbers[] = {10,20,30};
//    std::cout << << std::endl;
    std::cout << "using default accumulate" << std::endl;
    std::cout << std::accumulate(numbers,numbers+3,init) << std::endl;
 
    std::cout << "using functional's accumulate" << std::endl;
    std::cout << std::accumulate(numbers,numbers+3,init,std::minus<int>()) << std::endl;
 
    std::cout << "using custom function" << std::endl;
    std::cout << std::accumulate(numbers,numbers+3,init, my_function) << std::endl;
 
    std::cout << "using custom object" << std::endl;
    std::cout << std::accumulate(numbers,numbers+3,init, my_object) << std::endl;
 
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-09-08,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 二维数组
  • STL
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档