4 矩阵乘法的实现,如下:
#include "matrix.hpp" #include "accumulate_iterator.hpp" #include#1#处说明:#include template matrix operator * (matrix const &m0, matrix const &m1) throw (std::runtime_error) { // 矩阵尺寸不符合时,无法相乘。抛出一个运行期异常 if (m0.num_col() != m1.num_row()) throw std::runtime_error("Bad matrix size for multiplication."); matrix m(m0.num_row(), m1.num_col()); typename matrix ::iterator pos = m.begin(); for (size_t i = 0; i < m.num_row(); ++i) { for (size_t j = 0; j < m.num_col(); ++j) { *pos = 0; std::transform(m0.row_begin(i), m0.row_end(i),m1.col_begin(j),accumulater(*pos, std::plus ()),std::multiplies ());//这里注意transform的实现#1# ++pos; } } return m; }
templateOutputIterator transform (InputIterator first1, InputIterator last1,InputIterator first2,OutputIterator result, BinaryOperator binary_op) { while (first1 != last1) { *result=binary_op(*first1,*first2++);//注意前面#1#处result是累加迭代器,其赋值操作实质是累加。first2是个列迭代器 ++result;//累加迭代器自增是返回自身 ++first1; } return result; }