sum/multiply (1) |
template <class InputIterator1, class InputIterator2, class T> T inner_product (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, T init); |
---|---|
custom (2) |
template <class InputIterator1, class InputIterator2, class T, class BinaryOperation1, class BinaryOperation2> T inner_product (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, T init, BinaryOperation1 binary_op1, BinaryOperation2 binary_op2); |
inner_product 通过初始化具有 Init
的 累加器 acc 然后进行修改其计算结果为: acc = acc + (*i1) * (*i2) - 或 - acc = Binary_Op1(acc, Binary_Op2(*i1,
*i2)对范围 [First, Last) 的每在范围 [First2, First2 的迭代器 i1和迭代器 i2+
(Last - First)按顺序。
#include "algostuff.hpp"
#include <numeric>
#include <iterator>
#include <ostream>
using namespace std;
int main(){
list<int> coll;
INSERT_ELEMENTS(coll,1,6);
PRINT_ELEMENTS(coll);
//(0+1×1 +2×2 +3×3+4×4+5*5+6*6)
cout<<"inner reverse product:"<<inner_product(coll.begin(),coll.end(),coll.begin(),0)<<endl;
//(0+1×6 +2×5+3×4+4×3+5*2+6*1)
cout<<"inner reverse product:"<<inner_product(coll.begin(),coll.end(),coll.rbegin(),0)<<endl;
//(1* 1+1 * 2+2 * 3+3 * 4+4 * 5+5 * 6+6)
cout<<"product of sums:"<<inner_product(coll.begin(),coll.end(),coll.begin(),1,multiplies<int>(),plus<int>())<<endl;
return 0;
}
编译后输出:
1 2 3 4 5 6 inner reverse product:91
inner reverse product:56
product of sums:46080