C++模板实战8:矩阵乘法(二)

2014-11-24 07:38:48 · 作者: · 浏览: 2
ate class accumulate_iterator : public std::iterator { T &ref_x; // 累计所用变量引用 BinFunc bin_func; // 累计所用函数。ref_x = bin_func(ref_x, v) public: accumulate_iterator(T &ref_x, BinFunc bin_func) : ref_x(ref_x), bin_func(bin_func) {} // 去引用操作返回自身 accumulate_iterator operator*() {return *this;} // 赋值操作实现累计 template T0 const & operator=(T0 const &v) {ref_x = bin_func(ref_x, v);} accumulate_iterator& operator++() {return *this;} }; // 生成accumulate_iterator的助手函数 template accumulate_iterator accumulater(T &ref_x, BinFunc bin_func) { return accumulate_iterator (ref_x, bin_func); }
4 矩阵乘法的实现,如下:

#include "matrix.hpp"
#include "accumulate_iterator.hpp"
#include 
  
   
#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; }
           
          
         
        
       
      
     
    
   
  
#1#处说明:

template 
  
   
  OutputIterator 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;
}