向量向量和自定义类之间的差异

时间:2011-03-13 13:22:42

标签: c++ vector matrix

我想知道当使用矢量矢量来表示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 ) ;
}

编辑:忽略调整大小方法,因为Erik指出它不会保留原始数据。我只为一个我不介意的具体任务添加了。基本类只是ctor和()运算符。

1 个答案:

答案 0 :(得分:2)

  • - .resize()不会将现有数据保留在原始位置。
  • - 语法差异,operator()operator[]
  • - 没有迭代器,也没有使用例如std::算法
  • + 更好的位置,支持向量具有连续的内存
  • + 更易理解的初始化语法
  • + 保证阵列没有锯齿状

简而言之,该课程很好,可能更适合专业用途,但在通用目的方面表现不佳。