运用数值算法之前必须包含头文件<numeric>
1.加工运算后产生结果
对序列进行某种运算
- T accumulate( InputIterator beg, InputIterator end, T initValue)
- T accumulate( InputIterator beg, InputIterator end, T initValue, BinaryFunc op)
- 对于序列:
- a1, a2, a3, a4, ...
- 第一种形式计算并返回:initValue + a1 + a2 + a3 + ...
- 第二种形式计算并返回:initValue op a1 op a2 op a3 op ...(即将上式中的operator+变成op)
计算两序列的内积(Innner Product)
- T inner_product( InputIterator beg1, InputIterator end1, InputIterator beg2, T initValue)
- T inner_product( InputIterator beg1, InputIterator end1, InputIterator beg2, T initValue, BinaryFunc op1, BinaryFunc op2)
- 对于序列:
- a1, a2, a3, a4,...
- b1, b2, b3, b4,...
- 第一种形式计算并返回:initValue + (a1*b1)+(a2*b2)+ (a3*b3)+(a4*b4)+...
- 第二种形式计算并返回:initValue op1 ( a1 op2 b1) op1 ( a2 op2 b2) op1 ( a3 op2 b3) op1...(即将上式中的operator+变成op1, operator*换成op2)
// STL.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <print.hpp>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
vector<int> coll;
INSERT_ELEMENTS(coll,1,6);
PRINT_ELEMENTS(coll);
//1*1*2*3*4*5*6
cout<<"accumulate: "<<accumulate(coll.begin(),coll.end(),1,multiplies<int>())<<endl;
//1*(1+1)*(2+2)*(3+3)*(4+4)*(5+5)*(6+6)
cout<<"inner_product: "<<inner_product(coll.begin(),coll.end(),coll.begin(),1,multiplies<int>(),plus<int>())<<endl;
return 0;
}
2.相对值和绝对值之间的转换
将相对值转换成绝对值
- OutputIterator partial_sum( InputIterator sourceBeg, InputIterator sourceEnd, OutputIterator destBeg ) //返回目标区间内第一个未被覆盖的元素位置
- OutputIterator partial_sum( InputIterator sourceBeg, InputIterator sourceEnd, OutputIterator destBeg, BinaryFunc op)
- 对于序列:a1, a2, a3, a4...
- 第一种形式计算并将结果复制到destBeg起始的区间:a1, a1+a2, a1+a2+a3, a1+a2+a3+a4,....
- 第二种形式计算并将结果复制到destBeg起始的区间:a1, a1 op a2, a1 op a2 op a3, a1 op a2 op a3 op a4,....(即将上式中的operator+变成op)
将绝对值转换成相对值
- OutputIterator adjacent_difference( InputIterator sourceBeg, InputIterator sourceEnd, OutputIterator destBeg)
- OutputIterator adjacent_difference( InputIterator sourceBeg, InputIterator sourceEnd, OutputIterator destBeg, BinaryFunc op)
- 对于序列:a1, a2, a3, a4,...
- 第一种形式计算并将结果复制到destBeg起始的区间:a1, a2-a1, a3-a2 , a4-a3 , a5-a4, ...
- 第二种形式计算并将结果复制到destBeg起始的区间:a1, a2 op a1, a3 op a2 , a4 op a3 , a5 op a4, ...(即将上式中的operator-变成op)
// STL.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <print.hpp>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
vector<int> coll;
coll.push_back(17);
coll.push_back(-3);
coll.push_back(22);
coll.push_back(13);
coll.push_back(13);
coll.push_back(-9);
PRINT_ELEMENTS(coll,"coll: ");
adjacent_difference(coll.begin(),coll.end(),coll.begin());
PRINT_ELEMENTS(coll,"relative: ");
partial_sum(coll.begin(),coll.end(),coll.begin());
PRINT_ELEMENTS(coll,"absoluate: ");
return 0;
}