美文网首页
C++ STL partial_sum 函数说明

C++ STL partial_sum 函数说明

作者: book_02 | 来源:发表于2020-06-06 21:47 被阅读0次

1. 说明

对范围[first,last)内的元素逐个求累加和,放在result容器中。

x表示范围[first,last)内的元素,y表示放在result容器中的结果,求解过程如下:

y0 = x0 
y1 = x0 + x1 
y2 = x0 + x1 + x2 
y3 = x0 + x1 + x2 + x3 
y4 = x0 + x1 + x2 + x3 + x4 
... ... ...

函数签名如下:

template <class InputIterator, class OutputIterator>
OutputIterator partial_sum (InputIterator first, 
                            InputIterator last,
                            OutputIterator result);

注意:

  1. result容器要有足够的容量,否则报越界错误

其他说明

  1. 可自定义"求和"运算符
template <class InputIterator, class OutputIterator, class BinaryOperation>
OutputIterator partial_sum (InputIterator first, 
                            InputIterator last,
                            OutputIterator result, 
                            BinaryOperation binary_op);

2. 头文件

#include <numeric>

3. 例子-求部分和数组


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


int main(int argc, char **argv) 
{  
    std::vector<int> nums = { 1,2,3,4,5 };

    std::vector<int> psum;
    psum.resize(nums.size());
    
    partial_sum(nums.begin(), nums.end(), psum.begin());

    for (int num : psum) {
        std::cout << num << "\t";
    }

    return 0;
}

结果:

1       3       6       10      15      

4. 例子-求部分积数组


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


int main(int argc, char **argv) 
{  
    std::vector<int> nums = { 1,2,3,4,5 };

    std::vector<int> psum;
    psum.resize(nums.size());
    
    partial_sum(nums.begin(), nums.end(), psum.begin(), std::multiplies<int>());

    for (int num : psum) {
        std::cout << num << "\t";
    }

    return 0;
}

结果:

1       2       6       24      120      

使用了std::multiplies<int>()代替默认的求和运算

5. 参考

http://www.cplusplus.com/reference/numeric/partial_sum/
https://en.cppreference.com/w/cpp/algorithm/partial_sum

相关文章

  • C++ STL partial_sum 函数说明

    1. 说明 对范围[first,last)内的元素逐个求累加和,放在result容器中。 x表示范围[first,...

  • C++ STL transform 函数说明

    说明 简而言之,transform是用来做转换的。转换有两种:一元转换和二元转换。 一元转换是对容器给定范围内的每...

  • C++ STL iota 函数说明

    说明 iota用一个从value递增的数列给[first, last)的容器赋值等效于 C++11 才引入,之前版...

  • C++库

    标准库C++标准库,包括了STL容器,算法和函数等。C++ Standard Library:是一系列类和函数的集...

  • GeekBand C++ STL与泛型编程 第一周学习笔记

    STL概述 C++标准库包含STL和一些其他内容 STL有六大组件: 容器,分配器,算法,迭代器,适配器,仿函数 ...

  • [资源]C++ 程序员必收藏

    C++ 资源大全中文版 标准库 C++标准库,包括了STL容器,算法和函数等。 C++ Standard Libr...

  • 读书笔记17.06.03

    C++ STL:Listlist是C++标准模版库(STL,Standard Template Library)中...

  • [C++] STL 容器

    参考:[C++] STL 容器 (一) - 基本介紹[C++] STL 容器 (二) - Iterator 部分示例:

  • C++后端开发的踩坑整理

    C++开发的一些经验和踩坑整理 STL相关的坑 1. std::sort()函数要求严格弱序 STL文档中要求so...

  • C++ STL back_inserter 函数说明

    说明 back_inserter用于在末尾插入元素。实现方法是构造一个迭代器,这个迭代器可以在容器末尾添加元素。这...

网友评论

      本文标题:C++ STL partial_sum 函数说明

      本文链接:https://www.haomeiwen.com/subject/bdcgzhtx.html