创建一个连续的动态矩阵

时间:2019-09-14 07:26:08

标签: c++ c++17

数组具有作为连续内存块的良好特性。使用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)并不指向大小为#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; } 的连续块。如何在C ++中做到这一点?我只是遵守最新的标准(即C ++ 17)而已。我想要一个不涉及STL容器或外部库的答案。

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

function buildGrid() {
  const cards = $('.team-grid .card');
   for(let i = 0; i < cards.length; i+=3) {
    cards.slice(i, i+3).wrapAll('<div class="card-row"></div>');
  }
}

buildGrid();

function bioContainer() {
  // jQuery version that works
  //$('<div class="bio-wrapper"></div>').appendTo('.card-row');

  // Vanilla version that only works on the first instance of .card-row
  const block_to_insert = document.createElement('div');
  block_to_insert.className = 'bio-wrapper';

  const container_block = document.querySelectorAll('.card-row');
  // Suggested by @eugene-sunic
  for (let i = 0; i < container_block.length; i++) {
    container_block[i].appendChild(block_to_insert);
  }
}

2 个答案:

答案 0 :(得分:3)

这就是您正在做的事情,几乎完全一样,但是没有不连续的内存:

#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. 最好遵循@Someprogrammerdude的建议,并使用算术而不是指针数组。

答案 1 :(得分:1)

我还是不知道您要什么。要将矩阵元素存储在连续的位置,只需为它们分配一维动态数组的内存即可。已经讨论了两个基本选项,或者使用向量:

std::vector<int> mat(m * n);

,或者,如果它的内存开销对您来说很重要,请使用唯一的指针:

auto mat = std::make_unique<int[]>(m * n);

然后,要访问具有i行索引和j列索引的元素,只需使用:

a_i_j = mat[i * n + j];

假设m是行数,n是列数。此公式以所谓的 row-major 顺序存储元素。如果您需要主要列顺序,请切换至:

a_i_j = mat[j * m + i];

当然,整个方法最好使用一些getter运算符mat(i, j);封装在一个类中。