C++ STL算法之accumulate函数
来源:互联网 发布:证大财富 淘宝达人贷 编辑:程序博客网 时间:2024/05/21 06:21
1. 介绍
用来计算特定范围内(包括连续的部分和初始值)所有元素的和,除此之外,还可以用指定的二进制操作来计算特定范围内的元素结果。其头文件在numeric中。
accumulate原函数声明定义如下:
template<class InputIterator, class Type> Type accumulate( InputIterator _First, InputIterator _Last, Type _Val );template<class InputIterator, class Type, class Fn2> Type accumulate( InputIterator _First, InputIterator _Last, Type _Val, BinaryOperation _Binary_op );
参数说明。
但看说明也许不太容易懂,我们通过例子更具体的解释下这个函数。
2. 应用举例
#include <vector>#include <numeric>#include <functional>#include <iostream>using namespace std;int main( ) { vector <int> v1, v2( 20 ); vector <int>::iterator Iter1, Iter2; int i; for ( i = 1 ; i < 21 ; i++ ) { v1.push_back( i ); } cout << "最初向量v1中个元素的值为:\n ( " ; for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ ) cout << *Iter1 << " "; cout << ")." << endl; // accumulate函数的第一个功能,求和 int total; total = accumulate ( v1.begin ( ) , v1.end ( ) , 0 ); cout << "整数从1到20的和为: " << total << "." << endl; // 构造一个前n项和的向量 int j = 0, partotal; for ( Iter1 = v1.begin( ) + 1; Iter1 != v1.end( ) + 1 ; Iter1++ ) { partotal = accumulate ( v1.begin ( ) , Iter1 , 0 ); v2 [ j ] = partotal; j++; } cout << "前n项和分别为:\n ( " ; for ( Iter2 = v2.begin( ) ; Iter2 != v2.end( ) ; Iter2++ ) cout << *Iter2 << " "; cout << ")." << endl << endl; // accumulate函数的第二个功能,计算连乘积 vector <int> v3, v4( 10 ); vector <int>::iterator Iter3, Iter4; int s; for ( s = 1 ; s < 11 ; s++ ) { v3.push_back( s ); } cout << "向量v3的初始值分别为:\n ( " ; for ( Iter3 = v3.begin( ) ; Iter3 != v3.end( ) ; Iter3++ ) cout << *Iter3 << " "; cout << ")." << endl; int ptotal; ptotal = accumulate ( v3.begin ( ) , v3.end ( ) , 1 , multiplies<int>( ) ); cout << "整数1到10的连乘积为: " << ptotal << "." << endl; // 构造一个前n项积的向量 int k = 0, ppartotal; for ( Iter3 = v3.begin( ) + 1; Iter3 != v3.end( ) + 1 ; Iter3++ ) { ppartotal = accumulate ( v3.begin ( ) , Iter3 , 1 , multiplies<int>( ) ); v4 [ k ] = ppartotal; k++; } cout << "前n项积分别为:\n ( " ; for ( Iter4 = v4.begin( ) ; Iter4 != v4.end( ) ; Iter4++ ) cout << *Iter4 << " "; cout << ")." << endl;}
编译运行,看一下输出结果:
1 0
- C++ STL算法之accumulate函数
- STL算法之accumulate函数学习
- C++ STL算法之accumulate函数
- c++STL之accumulate
- STL算法 count_if函数 accumulate函数
- stl中的accumulate算法
- STL之accumulate
- STL泛型算法--accumulate()
- STL算法——accumulate
- accumulate算法函数求和示例
- C++ STL算法系列3---求和:accumulate
- C++ STL算法系列3---求和:accumulate
- C++ STL算法系列3---求和:accumulate
- C++ STL算法系列3---求和:accumulate
- C++ STL算法系列3---求和:accumulate
- C++ STL算法系列3---求和:accumulate
- STL中accumulate函数的使用
- STL中accumulate函数的使用
- 关系型数据库与NOSQL
- Android自定义属性,format详解
- KMP,深入讲解next数组的求解
- 打车软件的未来发展方向
- 通过DatabaseMetaData对象获得数据库元数据信息
- C++ STL算法之accumulate函数
- Windows下编译OpenSSL最新版(openssl-1.0.2a)
- Noip04合唱队形题解
- C++中const用法总结
- Eclipse学习心得
- 向Web站点发送GET请求、POST请求
- RQNOJ143 题解 、、
- Python 垃圾回收机制
- Implicit intents with startService are not safe错误的解决方式