第十五周项目阅读程序(3)

本文通过一个具体的C++程序示例,展示了如何利用STL中的数值算法如accumulate、inner_product、partial_sum及adjacent_difference等进行数组操作,并详细解释了这些函数的功能和用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*
 *Copyright(c) 2016, 烟台大学计算机与控制工程学院
 *All rights reserved.
 *文件名称:main.cpp
 *作    者:李德坤
 *完成日期:2016年6月4日
 *版本号:v1.0
 *
 *问题描述:阅读程序(3)
 *输入描述:无
 *输出描述:无
 */
#include <algorithm>
#include <functional>
#include <vector>
#include <iostream>
#include <numeric>
#include <iterator>
using namespace std;
int main()
{
    int a[] = {1,4,7,2,5,8};
    int b[] = {1,2,3,3,2,1};
    const int ASZ = sizeof a / sizeof a[0];//ASZ=6
    const int BSZ = sizeof b / sizeof b[0];//BSZ=6
    ostream_iterator<int> out(cout,"  ");//定义输出迭代器
    copy(a, a + ASZ, out);//输出数组a
    cout<<endl;
    copy(b, b + BSZ, out);//输出数组b
    cout<<endl;
    int r = accumulate(a, a + ASZ, 0);//r=0+1+4+7+2+5+8=27
    cout << "accumulate 1: " << r << endl;
    // Should produce the same result:
    r = accumulate(b, b + BSZ, 0, plus<int>());//0+1+2+3+3+2+1=12
    cout << "accumulate 2: " << r << endl;
    r = inner_product(a, a + ASZ, b, 0);
    // 或  r = inner_product(a, a + ASZ, b, 0, plus<int>(), multiplies<int>());
    //inner_product返回作为两个序列乘积而生成的元素的总和。步调一致地检查两个序列,将
    //来自两个序列的元素相乘,将相乘的结果求和。由 init 指定和的初值。假定从
    //beg2 开始的第二个序列具有至少与第一个序列一样多的元素,忽略第二个序列
    //中超出第一个序列长度的任何元素。init 的类型决定返回类型。
    cout << "inner_product : " << r << endl;
    int* it = partial_sum(a, a + ASZ, b);
    // 或 int* it = partial_sum(a, a + ASZ, b, plus<int>());
    //a,a+ASZ是输入序列,b是输出序列
    //将输入序列中每个元素与其先前所有元素的和写入对应位置的输出序列中. 
    copy(b, it, out);//输出b
    cout<<endl;
    it = adjacent_difference(a, a + ASZ, b);
    // 或 it = adjacent_difference(a, a + ASZ, b, minus<int>());
    //对于给定的序列x0,x1,...,x(n-1),计算序列中相邻两个元素的差序列x1-x0,x2-x1,...,x(n-1)-x(n-2)。该算法可以把结果序列保存在原序列中,也可以保存在另一个区间中。
    //除了比较出差值,还可以作给定的交互。
    //第一个元素是不变的放入结果中的。
    //adjacent_difference() 是数值算法,使用 <numeric> 头文件。
    copy(b, it, out);//输出b
    cout<<endl;
    return 0;
}
/*
输出结果为:
1  4  7  2  5  8
1  2  3  3  2  1
accumulate 1: 27
accumulate 2: 12
inner_product : 54
1  5  12  14  19  27
1  3  3  -5  3  3
*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值