函数模板:
//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.c