简体   繁体   English

在不循环c ++的情况下对2D数组进行分区

[英]partition a 2D array without looping c++

Im fairly new to c++ and am trying to program strassen's algorithm to multiply matrices. 我是一个相当新的c ++,我正在尝试编程strassen的算法来乘法矩阵。 Part of the algorithm requires me to partition a matrix into four parts eg 部分算法要求我将矩阵划分为四个部分,例如

4 5 6 7
6 7 8 9
1 2 3 4
2 3 5 6

partitioned: 分区:

4 5   6 7
6 7   8 9

1 2   3 4
2 3   5 6

(each part is then used again recursively and partitioned). (然后递归地再次使用每个部分并进行分区)。 I want to partition the matrices without looping and copying the data from the original matrix (as this would take more time). 我想分割矩阵而不循环和复制原始矩阵中的数据(因为这将花费更多的时间)。 The book i am reading says the matrices are partitioned using 'index calculations, identifying a submatrix by a range of row indices and a range of column indices of the original matrix.i am not sure what is meant by this. 我正在阅读的书说,使用'索引计算来划分矩阵,通过一系列行索引和原始矩阵的一系列列索引来识别子矩阵。我不确定这是什么意思。

Also, im not sure whether i should be using 2D arrays or vectors? 另外,我不确定我是否应该使用2D数组或向量? Ive seen alot of people recommending vectors but ive already written everything so far in 2D arrays so im hoping what i want is possible with 2D arrays. 我见过很多人推荐矢量但是我已经在2D阵列中编写了所有内容,所以我希望我想要的是2D阵列。

ps it can be assumed the dimensions of the matrices will always be a power of 2 and be nxn (square). ps可以假设矩阵的维数总是2的幂并且是nxn(正方形)。 Also, i have seen alot of questions similar to this but none of them actually have the solution i am looking for. 此外,我已经看到了很多与此类似的问题,但它们实际上都没有我想要的解决方案。

Thanks 谢谢

You can create a matrix class that supports directly sub-matrices as views: 您可以创建一个矩阵类,直接支持子矩阵作为视图:

template<typename T>
struct Matrix {
    int rows, cols, stride;
    std::vector<T> data; // Possibly empty for a view
    T *ptr;

    // A fresh matrix (owning its data)
    Matrix(int rows, int cols)
        : rows(rows), cols(cols), stride(cols),
          data(rows*cols),
          ptr(&data[0])
    {
    }

    // A view of a sub-matrix (pointing to the original data!)
    Matrix(Matrix& m, int row0, int col0, int rows, int cols)
        : rows(rows), cols(cols), stride(m.stride),
          ptr[&m(row0, col0)]
    {
    }

    T& operator()(int row, int col) {
        return ptr[row*stride + col];
    }

    ...
};

Of course you need to ensure that views don't outlive the owning matrix and you need to pay attention to what you want to mean to copy a view object if that operation is not forbidden. 当然,您需要确保视图不会超过拥有矩阵,并且如果不禁止该操作,则需要注意复制视图对象的意义。

Adding explicit operations like transforming a view into an owning matrix can be useful (if a copy constructor is not going to do that). 添加显式操作(如将视图转换为拥有矩阵)可能很有用(如果复制构造函数不打算这样做)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM