STL之inner_product

来源:互联网 发布:图集软件 编辑:程序博客网 时间:2024/05/17 07:33

需要的头文件:
numeric

源码:

//版本1template <class _InputIterator1, class _InputIterator2, class _Tp>_Tp inner_product(_InputIterator1 __first1, _InputIterator1 __last1,                  _InputIterator2 __first2, _Tp __init){  for ( ; __first1 != __last1; ++__first1, ++__first2)    __init = __init + (*__first1 * *__first2);  return __init;}//版本2template <class _InputIterator1, class _InputIterator2, class _Tp,          class _BinaryOperation1, class _BinaryOperation2>_Tp inner_product(_InputIterator1 __first1, _InputIterator1 __last1,                  _InputIterator2 __first2, _Tp __init,                   _BinaryOperation1 __binary_op1,                  _BinaryOperation2 __binary_op2){  for ( ; __first1 != __last1; ++__first1, ++__first2)    __init = __binary_op1(__init, __binary_op2(*__first1, *__first2));  return __init;}

作用:
计算[firtst1,last1)和[first2, first2+(last1-first1))的一般内积
通过二元仿函数我们可以取代 operator* 和 operator+

例子:

//请使用比较完整支持c++11特性的编译器进行编译#include <numeric>#include <iostream>#include <vector>#include <functional>using namespace std;int main(){    int ia[5] = { 1,2,3,4,5 };    vector<int> iv(ia, ia + 5);    int init = 10;    //计算内积    //   1  2  3  4  5    //   *  *  *  *  *    //   1  2  3  4  5    // -----------------// init+ 1+ 4+ 9+ 16+25 = 10+55 =65    cout << inner_product(iv.begin(), iv.end(), iv.begin(), init) << endl;    //   1  2  3      //   *  *  *      //   3  4  5     // -----------------// init+ 3+ 8+ 15 = 10+26 =36    cout << inner_product(iv.begin(), iv.begin() + 3, iv.begin() + 2, init) << endl;    //利用仿函数代替operator* 和 operator+    //   1  2  3  4  5    //   +  +  +  +  +    //   1  2  3  4  5    // -----------------// init- 1- 4- 9- 16-25 = -20    cout << inner_product(iv.begin(), iv.end(), iv.begin(), 10, minus<int>(), plus<int>()) << endl;    return 0;}

注意:

  • 必须提供一个初始值init,这么做的原因之一是当[first1,last1)为空时,任然可以获得一个明确的值

  • 在使用二元仿函数时,所有运算行为的顺序都有明确的设定

  • 注意binary_op1 和 binary_op2 使用时的区别
0 0