矩阵的转置
转置用一维数组描述的二维矩阵,类中实现,可拆解出来。如若是二维数组的转置。可以考虑二维转一维再转置。。。
当然,你愿意的话。。。(数据结构、算法与应用C++描述第七章习题)
matrix类
//matrix.h
template<class T>
class matrix
{
friend std::ostream& operator<<
(std::ostream& out, const matrix<T>& theMatrix);
public:
matrix(int theRows = 0, int theColumns = 0);
matrix(const matrix<T>& theMatrix);
...
matrix<T> tranpose();
T& operator() (int i, int j) const;//类似数学中的访问
...
private:
int rows, columns;
T* element;
};
template<class T>
matrix<T>::matrix(int theRows, int theColumns)
{//构造函数
if (theRows < 0 || theColumns < 0)
throw illegalParameterValue("Rows and columns must be >= 0");
if ((theRows == 0 || theColumns == 0)
&& (theRows != 0 || theColumns != 0))
throw illegalParameterValue
("Either both or neither rows and columns should be zero");
rows = theRows;
columns = theColumns;
element = new T[rows * columns];
}
template<class T>
matrix<T>::matrix(const matrix<T>& theMatrix)
{//复制构造
rows = theMatrix.rows;
columns = theMatrix.columns;
element = new T[rows * columns];
std::copy(theMatrix.element, theMatrix.element + rows * columns, element);
}
转置实现
template<class T>
matrix<T> matrix<T>::tranpose()
{//矩阵转置
matrix<T> w(columns, rows);
//用i遍历完一维数组,利用除法和求余锁定步长
for (int i = 0; i < rows * columns; ++i)
w.element[i / columns + rows * (i % columns)] = element[i];
return w;
}
//官方答案
template<class T>
void matrix<T>::transpose(matrix<T>& b)
{// Set b to be the transpose of *this.
// create result matrix
b.theRows = theColumns;
b.theColumns = theRows;
delete [] b.element;
b.element = new T [theRows * theColumns];
// copy from this->element to b.element
int ct = 0; // next element to move into the transpose
for (int i = 1; i <= theRows; i++)
for (int j = 1; j <= theColumns; j++)
b.element[(j - 1) * theRows + i - 1] = element[ct++];
}
测试
#include <iostream>
#include "matrix.h"
using namespace std;
int main()
{
try
{
matrix<int> x(3, 2), y, z;
int i, j;
for (i = 1; i <= 3; i++)
for (j = 1; j <= 2; j++)
x(i, j) = 2 * i + j;
cout << "Initialized x(i,j) = 2*i + j" << endl;
cout << "x(3,1) = " << x(3, 1) << endl;
cout << "x is" << endl;;
cout << x << endl;
y = x.tranpose();
cout << y << endl;
}
catch (...) {
cerr << "An exception has occurred" << endl;
}
return 0;
}
输出
Initialized x(i,j) = 2*i + j
x(3,1) = 7
x is
3 4
5 6
7 8
3 5 7
4 6 8