网站建设翻译英文是什么,视觉中国的图片可以拿来做网站,百度一下你就知道123,建设网站公司兴田德润i优惠吗如果你需要处理一个数组的前缀和#xff0c;或者数组中某一段元素的前缀和#xff0c;你会怎么做呢#xff1f; partial_sum函数是STL中的函数#xff0c;用于计算范围的部分和#xff0c;并从结果开始分配范围中的每个元素#xff0c;range[first,last)中相应元素的部分… 如果你需要处理一个数组的前缀和或者数组中某一段元素的前缀和你会怎么做呢 partial_sum函数是STL中的函数用于计算范围的部分和并从结果开始分配范围中的每个元素range[first,last)中相应元素的部分和。
头文件
numeric需要使用命名空间std。 声明
C11中有partial_sum函数的两种重载
templatetypename _InputIterator, typename _OutputIterator_OutputIteratorpartial_sum(_InputIterator __first, _InputIterator __last,_OutputIterator __result)templatetypename _InputIterator, typename _OutputIterator,typename _BinaryOperation_OutputIteratorpartial_sum(_InputIterator __first, _InputIterator __last,_OutputIterator __result, _BinaryOperation __binary_op)该函数是用模板类写的因此可以对vector数组进行操作。
函数的参数定义如下
__first迭代到序列中的初始位置Start of input range__last迭代到序列中的最终位置End of input range__result记录部分和结果的数组Output sum__binary_op定义“和”的二元运算Function object
在基本的使用中一般采用第一个重载。 示例
先看普通数组的例子
#includeiostream
#includenumeric
int main()
{int a[6]{1,1,4,5,1,4};int res1[6],res2[2];std::partial_sum(a,a6,res1);//a[0]~a[5]for(auto item : res1)printf(%d ,item);putchar(\n);std::partial_sum(a1,a3,res2);//a[1]~a[2]for(auto item : res2)printf(%d ,item);return 0;
}运行结果
需要注意的是如果想计算到a[i]处的部分和__last参数必须传入ai1。 vector数组的例子
#includeiostream
#includenumeric
#includevector
using namespace std;
int main()
{vectorint v{2,0,2,4,2,2};vectorint res(6);partial_sum(v.begin(),v.end(),res.begin());for(auto item : res)printf(%d ,item);return 0;
}运行结果