【问题标题】:Difference between vector of vectors and custom class向量的向量和自定义类之间的区别
【发布时间】:2011-03-13 13:22:41
【问题描述】:

我想知道当使用向量的向量来表示二维矩阵或创建一个类时(任何类型的)有什么区别:

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 和 () 运算符。

【问题讨论】:

    标签: c++ vector matrix


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

    简而言之,该类很好,并且对于专门用途可能更好,但在通用用途方面表现不佳。

    【讨论】:

    • 好吧,让我们忽略该方法,我只为我不介意数据位置的特定任务添加它。基本类是 ctor 和 () 运算符。
    • 其他差异可能是不同的语法([] vs ()),缺少迭代器,不能与 std:: 算法一起使用......你真正要问的是什么?你的方法会奏效,并且由于你的支持向量是连续的,它将确保更好的局部性。
    • 嗯,我使用矩阵进行数值计算,并且连续的内存地址是我关心的一件事......向量向量不能保证这一点?暂时我不使用和 std::algorithms ..
    • 单个向量具有连续内存。向量的向量将具有指向其他 T 的连续数组的指针的连续数组
    猜你喜欢
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 2015-08-11
    • 2010-11-01
    • 2013-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多