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和()運算符。
那麼好吧,讓我們忽略這種方法,我只是將它添加到一個特定的任務,我不介意數據的位置。基本類是ctor和()運算符。 – alexT
那麼其他的差異可能是不同的語法('[]'vs'()'),缺少迭代器,不能用於std :: algorithms ......你真的在問什麼?你的方法將起作用,並且由於你的支持矢量是連續的,它將確保更好的局部性。 – Erik
已更新的答案。 – Erik