template <class T>
SparseMatrix<T> SparseMatrix<T>::Multiply(SparseMatrix<T>& b) {
SparseMatrix<T> result(Rows, b.Cols);
if (Cols != b.Rows) {
cerr << "Incompatible matrices" << endl;
return result;
}
if (Terms == maxTerms || b.Terms == maxTerms) {
cerr << "One additional space in a or b needed" << endl;
return result;
}
int *rowSize = new int[b.Rows];
int *rowStart = new int[b.Rows + 1];
T *temp = new T[b.Cols];
int i, Current, lastInResult, RowA, ColA, ColB;
for (i = 0; i < b.Rows; i ++) {
rowSize[i] = 0;
}
for (i = 0; i < b.Terms; i ++) {
rowSize[smArray[i].row] ++;
}
rowStart[0] = 0;
for (i = 1; i <= b.Rows; i ++) {
rowStart[i] = rowStart[i - 1] + rowSize[i - 1];
}
Current = 0;
lastInResult = -1;
while (Current < Terms) {
RowA = smArray[Current].row;
for (i = 0; i < b.Cols; i ++) {
temp[i] = 0;
}
while (Current < Terms && smArray[Current].row == RowA) {
ColA = smArray[Current].col;
for (i = rowStart[ColA]; i < rowStart[ColA + 1]; i ++) {
ColB = b.smArray[i].col;
temp[ColB] += smArray[Current].value * b.smArray[i].value;
}
Current ++;
}
for (i = 0; i < b.Cols; i ++) {
if (temp[i] != 0) {
lastInResult ++;
result.smArray[lastInResult].row = RowA;
result.smArray[lastInResult].col = i;
result.smArray[lastInResult].value = temp[i];
}
}
result.Rows = Rows;
result.Cols = b.Cols;
result.Terms = lastInResult + 1;
}
delete[] rowSize;
delete[] rowStart;
delete[] temp;
return result;
};