差分

2011-03-13 22 views
2

我想知道使用向量的向量來表示2D矩陣或使一個類等時(任何種類的)之差,就是:差分

template < class T > 
class Matrix2D { 
public: 
    Matrix2D(unsigned m, unsigned n) : m(m), n(n), x(m * n) {} ; 
    Matrix2D(const Matrix2D<T> &matrix) : m(matrix.m), n(matrix.n) x(matrix.x) {} ; 
    Matrix2D& operator= (const Matrix2D<T> &matrix) ; 
    T& operator()(unsigned i, unsigned j) ; 
    void resize(int nx, int ny) ; 
private: 
    unsigned m, n ; 
    std::vector<T> x ;   
} ; 


template <class T> 
T& Matrix2D<T>::operator()(unsigned i, unsigned j) { 
    return x[ j + n * i ] ; 
} 

template <class T> 
Matrix2D<T>& Matrix2D<T>::operator= (const Matrix2D<T> &matrix) { 
    m = matrix.m ; 
    n = matrix.n ; 
    x = matrix.x ; 
    return *this ; 
} 

template <class T> 
void Matrix2D<T>::resize(int nx, int ny) { 
    m = nx ; 
    n = ny ; 
    x.resize(nx * ny) ; 
} 

編輯:忽略resize方法,正如Erik指出的那樣,它不會保留原始數據的位置。我只是添加了一個我不介意的特定任務。基本類只是ctor和()運算符。

回答

2
  • -.resize()不會讓現有的數據在原來的位置上。
  • -語法差異,operator() VS operator[]
  • -沒有迭代器和沒有使用例如std::算法
  • +更好局部性,背襯載體具有連續存儲器
  • +初始化
  • 更容易理解語法
  • +保證該數組不是鋸齒狀

總之,這個類很好,可能更適合專門用途,但對於通用目的來說它不太好。

+0

那麼好吧,讓我們忽略這種方法,我只是將它添加到一個特定的任務,我不介意數據的位置。基本類是ctor和()運算符。 – alexT

+0

那麼其他的差異可能是不同的語法('[]'vs'()'),缺少迭代器,不能用於std :: algorithms ......你真的在問什麼?你的方法將起作用,並且由於你的支持矢量是連續的,它將確保更好的局部性。 – Erik

+0

已更新的答案。 – Erik