如何动态分配矩阵? [英] How do you dynamically allocate a matrix?

查看:66
本文介绍了如何动态分配矩阵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 C++ 中动态分配二维矩阵?我已经根据我已经知道的内容进行了尝试:

How do you dynamically allocate a 2D matrix in C++? I have tried based on what I already know:

#include <iostream>

int main(){
    int rows;
    int cols;
    int * arr;
    arr = new int[rows][cols];
 }

它适用于一个参数,但现在适用于两个.我该怎么办?

It works for one parameter, but now for two. What should I do?

推荐答案

矩阵实际上可以表示为数组的数组.

A matrix is actually can be represented as an array of arrays.

int rows = ..., cols = ...;
int** matrix = new int*[rows];
for (int i = 0; i < rows; ++i)
    matrix[i] = new int[cols];

当然,要删除矩阵,您应该执行以下操作:

Of course, to delete the matrix, you should do the following:

for (int i = 0; i < rows; ++i)
    delete [] matrix[i];
delete [] matrix;


我刚刚想到了另一种可能性:


I have just figured out another possibility:

int rows = ..., cols = ...;
int** matrix = new int*[rows];
if (rows)
{
    matrix[0] = new int[rows * cols];
    for (int i = 1; i < rows; ++i)
        matrix[i] = matrix[0] + i * cols;
}

释放这个数组更容易:

if (rows) delete [] matrix[0];
delete [] matrix;

这个解决方案的优点是为所有元素分配一个大内存块,而不是几个小块.不过,我发布的第一个解决方案是数组数组概念的更好示例.

This solution has the advantage of allocating a single big block of memory for all the elements, instead of several little chunks. The first solution I posted is a better example of the arrays of arrays concept, though.

这篇关于如何动态分配矩阵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆