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
- STL之inner_product
- STL 之accumulate,adjacent_difference,inner_product,partial_sum
- STL 之accumulate,adjacent_difference,inner_product,partial_sum
- STL系列------算法---------inner_product
- C++ STL inner_product
- inner_product
- inner_product
- inner_product例子
- 内积算法inner_product
- std::transform || inner_product || accumulate
- accumulate,inner_product,partial_sum,adjacent_difference
- 【STL】STL之map
- 【STL】STL之set
- 【STL】STL之pair
- 概念:Inner_Product(IP)层
- STL 5: STL之迭代器
- 【STL】STL容器之vector
- 【STL】STL容器之map
- 第五章 Transact—SQL 语句
- 优秀开源代码解读之JS与iOS Native Code互调的优雅实现方案
- Linux常用命令
- Android透明状态栏和沉浸式状态栏实现
- C++_子集生成算法汇总
- STL之inner_product
- TCP/IP发送图片,swing.JPanel显示并更新图片(一、图片显示和更新)
- return在try-catch-finally语句中的使用
- 详细解释数据挖掘中的 10 大算法(上)
- js变量、作用域及内存详解
- JSDoc命令行参数
- Android SDK无法下载,ADT官网无法打开解决方法
- 双目立体视觉简单介绍
- 详细解释数据挖掘中的 10 大算法(下)