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

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

问题描述

你如何动态地分配在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 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;
}

舷这个数组是简单:

Freeing this array is easier:

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天全站免登陆