Difference between vector of vectors and custom class
I was wondering what the difference (of any kind) is when u开发者_C百科sing a vector of vectors to represent a 2D matrix or make a class like:
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 ) ;
}
Edit: Ignore the resize method, as Erik pointed out it would not keep original data place. I only added for a specific task where I didn't mind. The basic class is just the ctor and the () operator.
- -
.resize()
will not keep existing data in the original positions. - - Syntax differences,
operator()
vsoperator[]
- - No iterators, and no using e.g.
std::
algorithms - + Better locality, backing vector has contiguous memory
- + More understandable syntax for initialization
- + Guarantees that the array isn't jagged
In short, the class is fine and likely better for specialized purposes, but it's not doing too well on generic-purpose.
精彩评论