向量的向量和自定义类之间的区别
我想知道使用向量向量表示 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 ) ;
}
编辑:忽略调整大小方法,正如埃里克指出的那样,它不会保留原始数据的位置。我只为我不介意的特定任务添加。基本类只是 ctor 和 () 运算符。
I was wondering what the difference (of any kind) is when using 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
.resize()
不会将现有数据保留在原始位置。operator()
与operator[]
std::
算法简而言之,该类很好,并且可能更适合特殊用途,但它在通用用途上表现不佳。
.resize()
will not keep existing data in the original positions.operator()
vsoperator[]
std::
algorithmsIn short, the class is fine and likely better for specialized purposes, but it's not doing too well on generic-purpose.