C++超详细讲解稀疏矩阵

  void storesum(term a[],int *totald,int row,int column,int *sum)

  {//如果 *sum!=0,它的行和列存储位置为 d 中的 *totald+1

  if(*sum)

  if(*tptald

  {

  d[++*totald].row=row;

  d[*totald].col=column;

  d[*totald].value=*sum;

  *sum=0;

  }

  else{

  fprintf(stderr,"Numbers of terms in product exceeds %d

  ",MAX_TERMS);

  exit(1);

  }

  }

  void mmult(term a[], term b[], term d[])

  //将两个稀疏矩阵相乘

  {

  int i,j,column,totalb=b[0].value,totald=0;

  int rows_a=a[0].row,cols_a=a[0].col;

  totala=a[0].value;int cols_b=b[0].col;

  int row_begin=1, row=a[1].row, sum=0;

  int new_b[MAX-TERMS][3];

  if(cols_a!=b[0].row){

  fprintf(stderr,"Incompatible matrices

  ");

  exit(1);

  }

  fast_transpose(b.new_b);

  //设置边界条件

  a[totala+1].row=rows_a;

  new_b[totalb+1].row=cols_b;

  new_b[totalb+1].col=0;

  for(i=1;i<=totala;){

  column=new_b[1].row;

  for(j=1;j<=totalb+1;){

  //将a的行乘以b的列

  if(a[i].row!=row){

  storesum(d,&totald,row,column,&sum);

  i=row_begin;

  for(;new_b[j].row==column;j++)

  ;

  column=new_b[j]. row;

  }

  else if(new_b[j].row!=column){

  storesum(d,&totald,row,column,&sum);

  i=row_begin;

  column=new_b[j].row;

  }

  else switch(COMPARE(a[i].col,new_b[j].col)){

  case-1://转到a中的下一项

  i++;break;

  case 0://添加项,转到a和b的下一项

  sum+=(a[i++].value*new_b[j++].value); break;

  case 1://来到b的下一项

  j++;

  }

  }// for j<=totalb+1 结束循环

  for(;a[i].row==row;i++)

  ;

  row_begin=i;row=a[i].row;

  }//for i<=totala 结束循环

  d[0].row=rows_a;

  d[0].col=cols_b;d[0].value=totald;

  }