如何重塑矩阵?

cde*_*man 7 c++ matrix

我目前正在尝试将一些Python代码转换为C++.一个"小"问题是改变矩阵的尺寸.是否有可能在C++中重塑一个类似于Python reshape函数的矩阵?

例如,在Python中,我可以轻松地创建一个数组,numpy并轻松地重塑这些维度.

a = np.array([[1,2,3],[4,5,6]])
>>> a.reshape(3,2)
array([[1, 2],
       [3, 4],
       [5, 6]])
Run Code Online (Sandbox Code Playgroud)

我怎么能用C++做到这一点?也许这是一个简单的问题,但我完全无法做到这一点.我已经在OpenCV库中看到了这个Mat,但是对于MinGW而言,它被证明是非常难以正常工作,更不用说单个函数的大量添加了.如果"基本"功能可以实现这一点,那将是理想的选择.

Mar*_* A. 6

就内存连续放置(例如普通C数组),您可以使用不同的索引重新解释类型:

int array[2][3] =   {   { 1, 2, 3 },
                        { 4, 5, 6 } 
                    };

// Reinterpret the array with different indices
int(*array_pointer)[3][2] = reinterpret_cast<int(*)[3][2]>(array);

for (int x = 0; x < 3; ++x) {
    for (int y = 0; y < 2; ++y)
        std::cout << (*array_pointer)[x][y] << " ";
    std::cout << std::endl;
}
// Output:
// 1 2
// 3 4
// 5 6
Run Code Online (Sandbox Code Playgroud)

Example

以上只是一个示例,表明问题实际上归结为如何在矩阵类中布置内存.

如果您的类使用std::vector<int>带有线性索引的内部,则可以重新解释这些索引以满足您的访问模式.