用vector來實現matrix。

來源:互聯網
上載者:User

 

眾所周知,c++沒有提供預設的matrix(矩陣)類型。不過大部分時候我們可以

沿用c的用法,可以聲明一個二維數組來聲明matrix。本文描述了另外一種方法,

來實現一個matrix類,表達一個二維數組的概念,具體的實現是二維的vector。

 

 

#ifndef MATRIX_H

#define MATRIX_H

 

#include <vector>

using std::vector;

 

template <typename T>

class matrix

{

private:

   vector< vector<T> > vv;

   int row;

   int col;

public:

matrix(int rows, int cols):vv(rows), row(rows), col(cols)

{   

  for (int i = 0; i < row; ++i) //這個唯一的需要注意的地方是如何構造一個二維的vector。先構造一個vector< vector<> >,

                                            // 再初始化裡面的vector的長度。

  {

  vv[i].resize(cols);

  }

}

 

const vector<T>& operator[](int row) const 

{

  if (row >= this->row)

  {

      throw "index out of range";   // 這裡我們可以拋出自己定義的異常,也可以不這樣,因為vector也會檢查index是否越界。

  }

  return vv[row];

}

 

vector<T>& operator[](int row)  // 非const的版本,用來寫。通常編譯器會自動選擇匹配的函數來調用。

    if (row >= this->row)

   {

       throw "index out of range";

    }

    return vv[row]; 

}    

 

int getrownum() const { return row;} //取得行數

int getcolnum() const { return col;}   // 取得列數。

 

};

 

#endif

 

 

這裡我們不需要定義複製建構函式和賦值建構函式,因為預設的已經夠用了。

以上代碼經過vs2008編譯和測試。

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.