c++ - Create a contiguous dynamic matrix
问题描述
Arrays have this nice property of being contiguous blocks of memory. When using new
to allocate memory for an array, it returns a pointer to a contiguous block of memory. However, if I allocate a matrix using new
, like this:
#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;
}
This works, but mat
doesn't point to a contiguous block of size n * m * sizeof(int)
. How can I do this in C++? I am just complying to the latest standard (that is C++17) and nothing else. I want an answer that doesn't involve STL containers or external libraries.
Please don't answer about C, as that is pretty easy to do in both C99 and C11 using variable-length arrays:
#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
}
笔记:
- 这仍然是丑陋的代码......你可能最好创建一个适当的矩阵类,或者更好 - 使用其他人的实现。
- 最好遵循@Someprogrammerdude 的建议并使用算术而不是指针数组。
推荐阅读
- sql - Foreach row, update another table row if exist else insert a new record
- javascript - ReactJS + D3:解析本地 CSV 文件并使用 d3-request 将其传递给状态
- mongodb - 如何找到空的使用mongodb?
- php - Dynamic insert the template to the base template
- python - Loop through url-list in python
- python - Firefox 不保存带有扩展名的文件
- keyboard-events - Interaction with a running process
- c# - GroupPrincipal.FindByIdentity 未获取最新的 AD 组
- node.js - node.js 中间件使代码同步
- odoo - 未捕获的类型错误:无法读取未定义的属性“类型”