函数模板:
//iner_product.h #ifndef INNER_PRODUCT_H #define INNER_PRODUCT_H //版本1 template <typename InputIterator1, typename InputIterator2, typename T> T inner_product(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, T init) { for( ; first1 != last1; ++first1, ++first2) { init += *first1 * *first2; } return init; } //版本2 template <typename InputIterator1, typename InputIterator2, typename T, typename BinaryOperation1, typename BinaryOperation2> T inner_product(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, T init, BinaryOperation1 binary_op1, BinaryOperation2 binary_op2) { for( ; first1 != last1; ++first1, ++first2) { //用外界提供的函数对象来代替第一版本中的* + init = binary_op1(init, binary_op2(*first1, *first2)); } return init; } #endif
//main.cpp #include <vector> #include <iostream> #include "inner_product.h" #include <functional> using namespace std; int main(void) { int a[5] = {0, 1, 2, 3, 4}; vector<int> ivec(a, a+5); cout << inner_product(ivec.begin(), ivec.end(), ivec.begin(), 10) << endl; //40 cout << inner_product(ivec.begin(), ivec.end(), ivec.begin(), 10, minus<int>(), plus<int>()) << endl; //-10 system("pause"); return 0; }
0 1 2 3 4
0 1 2 3 4
1. 结果为 10 + 0*0 + 1*1 + 2*2 + 3*3 + 4*4 = 40
2. 结果为 10 - (0+0) - (1+1) - (2+2) - (3+3) - (4+4) = -10