创建连续的动态矩阵 [英] Create a contiguous dynamic matrix

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

问题描述

数组具有作为连续内存块的良好属性。当使用new为数组分配内存时,它返回指向连续挡路内存的指针。但是,如果我使用new分配一个矩阵,如下所示:

#include <iostream> //std::cin

int main()
{
    int n, m;
    std::cin >> n >> m;
    int** mat = new int*[n];
    for (int i = 0; i < n; i++)
        mat[i] = new int[m];
    //use the matrix in some way
    for (int i = 0; i < n; i++)
        delete[] mat[i];
    delete[] mat;
    return 0;
}

这是可行的,但是mat没有指向大小为n * m * sizeof(int)的连续挡路。我如何在C++中做到这一点?我只是遵循最新的标准(即C++17),没有别的。我需要一个不涉及STL容器或外部库的答案。

请不要回答有关C的问题,因为在C99和C11中使用可变长度数组都很容易做到这一点:

#include <stdio.h> //scanf
#include <stdlib.h> //malloc, free

int main()
{
    int n, m;
    scanf("%d %d", &n, &m);
    //int mat[n][m]; VLA, but I want dynamic
    int (*mat)[m] = malloc(n * sizeof *mat);
    //use the matrix in some way;
    free(mat);
    return 0;
}

推荐答案

下面是您正在执行的操作,几乎完全相同,但没有非连续内存:

#include <iostream> //std::cin
#include <memory>

int main()
{
    int n, m;
    std::cin >> n >> m;
    auto matrix_data = std::make_unique<int[]>(n * m);
    auto mat = std::make_unique<int[]>(n);
    for(int i = 0; i < n; i++) { mat[i] = matrix_data.get() + i * m; }

    // Use the matrix in some way

    // No need to free anything - we're using smart pointers.

    // No need to return 0 from main - that's the default
}

备注:

  1. 这仍然是难看的代码.您最好创建一个适当的矩阵类,或者最好还是使用别人的实现。
  2. 最好按照@SomeProgrammerdud的建议,使用算术,而不是指针数组。

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

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