C++實現矩陣的轉置


矩陣的轉置

轉置用一維數組描述的二維矩陣,類中實現,可拆解出來。如若是二維數組的轉置。可以考慮二維轉一維再轉置。。。
當然,你願意的話。。。(數據結構、算法與應用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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM