use*_*844 496 c++ arrays multidimensional-array dynamic-allocation
如何使用new声明二维数组?
就像,对于"普通"数组,我会:
int* ary = new int[Size]
Run Code Online (Sandbox Code Playgroud)
但
int** ary = new int[sizeY][sizeX]
Run Code Online (Sandbox Code Playgroud)
a)不工作/编译和b)没有完成什么:
int ary[sizeY][sizeX]
Run Code Online (Sandbox Code Playgroud)
确实.
Meh*_*ari 707
动态2D数组基本上是指向数组的指针数组.您可以使用循环初始化它,如下所示:
int** a = new int*[rowCount];
for(int i = 0; i < rowCount; ++i)
a[i] = new int[colCount];
Run Code Online (Sandbox Code Playgroud)
上面的for colCount= 5和for rowCount = 4将产生以下结果:

Kev*_*ney 291
int** ary = new int[sizeY][sizeX]
Run Code Online (Sandbox Code Playgroud)
应该:
int **ary = new int*[sizeY];
for(int i = 0; i < sizeY; ++i) {
ary[i] = new int[sizeX];
}
Run Code Online (Sandbox Code Playgroud)
然后清理将是:
for(int i = 0; i < sizeY; ++i) {
delete [] ary[i];
}
delete [] ary;
Run Code Online (Sandbox Code Playgroud)
编辑:正如Dietrich Epp在评论中指出的那样,这并不是一个轻量级的解决方案.另一种方法是使用一个大的内存块:
int *ary = new int[sizeX*sizeY];
// ary[i][j] is then rewritten as
ary[i*sizeY+j]
Run Code Online (Sandbox Code Playgroud)
Old*_*ier 199
虽然这个流行的答案会为您提供所需的索引语法,但它的效率却倍增:空间和时间都很大而且速度慢.还有更好的方法.
为什么答案大而慢
建议的解决方案是创建一个动态指针数组,然后将每个指针初始化为它自己的独立动态数组.这种方法的优点是它为您提供了您习惯的索引语法,因此如果您想在位置x,y处找到矩阵的值,您可以说:
int val = matrix[ x ][ y ];
Run Code Online (Sandbox Code Playgroud)
这是有效的,因为matrix [x]返回一个指向数组的指针,然后用[y]索引.打破它:
int* row = matrix[ x ];
int val = row[ y ];
Run Code Online (Sandbox Code Playgroud)
方便,是吗?我们喜欢[x] [y]语法.
但是解决方案有一个很大的缺点,那就是它既胖又慢.
为什么?
它既胖又慢的原因实际上是一样的.矩阵中的每个"行"是单独分配的动态数组.在时间和空间上进行堆分配都很昂贵.分配器花费时间进行分配,有时运行O(n)算法来完成分配.并且分配器为每个行数组"填充"额外的字节用于簿记和对齐.额外的空间成本......嗯...额外的空间.该释放器将还需要额外的时间,当你去解除分配矩阵,精心免费-ING了每个单排分配.想到这一点,让我流连忘返.
这是另一个原因,它很慢.这些单独的分配往往存在于不连续的内存部分.一行可能在地址1,000,另一行在地址100,000 - 您可以得到这个想法.这意味着当你遍历矩阵时,你就像一个狂野的人一样跳过记忆.这往往会导致缓存未命中,从而大大减慢处理时间.
因此,如果您绝对必须拥有可爱的[x] [y]索引语法,请使用该解决方案.如果你想要快速和小巧(如果你不关心那些,为什么你在使用C++?),你需要一个不同的解决方案.
不同的解决方案
更好的解决方案是将整个矩阵分配为单个动态数组,然后使用(略微)聪明的索引数学来访问单元格.索引数学只是非常聪明; 不,它根本不聪明:很明显.
class Matrix
{
...
size_t index( int x, int y ) const { return x + m_width * y; }
};
Run Code Online (Sandbox Code Playgroud)
鉴于此index()函数(我想象的是它是类的成员,因为它需要知道m_width矩阵),您可以访问矩阵数组中的单元格.矩阵数组的分配方式如下:
array = new int[ width * height ];
Run Code Online (Sandbox Code Playgroud)
所以在缓慢,肥胖的解决方案中相当于这个:
array[ x ][ y ]
Run Code Online (Sandbox Code Playgroud)
......这是一个快速,小巧的解决方案:
array[ index( x, y )]
Run Code Online (Sandbox Code Playgroud)
可悲,我知道.但你会习惯它.你的CPU会感谢你.
M. *_*gan 115
在C++ 11中,它是可能的:
auto array = new double[M][N];
Run Code Online (Sandbox Code Playgroud)
这样,内存不会被初始化.要初始化它,请执行以下操作:
auto array = new double[M][N]();
Run Code Online (Sandbox Code Playgroud)
示例程序(使用"g ++ -std = c ++ 11"编译):
#include <iostream>
#include <utility>
#include <type_traits>
#include <typeinfo>
#include <cxxabi.h>
using namespace std;
int main()
{
const auto M = 2;
const auto N = 2;
// allocate (no initializatoin)
auto array = new double[M][N];
// pollute the memory
array[0][0] = 2;
array[1][0] = 3;
array[0][1] = 4;
array[1][1] = 5;
// re-allocate, probably will fetch the same memory block (not portable)
delete[] array;
array = new double[M][N];
// show that memory is not initialized
for(int r = 0; r < M; r++)
{
for(int c = 0; c < N; c++)
cout << array[r][c] << " ";
cout << endl;
}
cout << endl;
delete[] array;
// the proper way to zero-initialize the array
array = new double[M][N]();
// show the memory is initialized
for(int r = 0; r < M; r++)
{
for(int c = 0; c < N; c++)
cout << array[r][c] << " ";
cout << endl;
}
int info;
cout << abi::__cxa_demangle(typeid(array).name(),0,0,&info) << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:
2 4
3 5
0 0
0 0
double (*) [2]
Run Code Online (Sandbox Code Playgroud)
Dan*_*lis 56
我从静态数组示例中假设您需要一个矩形数组,而不是锯齿状数组.您可以使用以下内容:
int *ary = new int[sizeX * sizeY];
Run Code Online (Sandbox Code Playgroud)
然后您可以访问以下元素:
ary[y*sizeX + x]
Run Code Online (Sandbox Code Playgroud)
别忘了使用delete [] ary.
Lev*_*son 43
在C++ 11及更高版本中,我建议使用两种常用技术,一种用于编译时维度,另一种用于运行时.两个答案都假设您需要均匀的二维数组(不是锯齿状的数组).
使用std::array的std::array,然后用new把它放在堆:
// the alias helps cut down on the noise:
using grid = std::array<std::array<int, sizeX>, sizeY>;
grid * ary = new grid;
Run Code Online (Sandbox Code Playgroud)
同样,这仅在编译时已知维度的大小时才有效.
完成仅在运行时已知的大小的二维数组的最佳方法是将其包装到类中.该类将分配一个1d数组,然后重载operator []以提供第一个维度的索引.这是有效的,因为在C++中,2D数组是行主要的:
(摘自http://eli.thegreenplace.net/2015/memory-layout-of-multi-dimensional-arrays/)
连续的内存序列有助于提高性能,并且易于清理.这是一个示例类,省略了许多有用的方法,但显示了基本的想法:
#include <memory>
class Grid {
size_t _rows;
size_t _columns;
std::unique_ptr<int[]> data;
public:
Grid(size_t rows, size_t columns)
: _rows{rows},
_columns{columns},
data{std::make_unique<int[]>(rows * columns)} {}
size_t rows() const { return _rows; }
size_t columns() const { return _columns; }
int *operator[](size_t row) { return row * _columns + data.get(); }
int &operator()(size_t row, size_t column) {
return data[row * _columns + column];
}
}
Run Code Online (Sandbox Code Playgroud)
所以我们创建一个带有std::make_unique<int[]>(rows * columns)条目的数组.我们重载operator []将为我们索引行.它返回一个int *指向行开头的行,然后可以将其解除引用为列的正常行.请注意,make_unique首先使用C++ 14,但如果需要,可以在C++ 11中对其进行填充.
这些类型的结构也过载也很常见operator():
int &operator()(size_t row, size_t column) {
return data[row * _columns + column];
}
Run Code Online (Sandbox Code Playgroud)
从技术上讲,我没有new在这里使用过,但是从使用/ std::unique_ptr<int[]>转到int *并使用new/ 是微不足道的delete.
Mar*_*som 29
这个问题是窃听我 - 这是一个足够常见的问题是一个很好的解决方案应该已经存在,东西比向量或滚动自己的数组索引的矢量更好.
当C++中存在某些东西但不存在时,首先要看的是boost.org.在那里,我找到了Boost多维数组库,multi_array.它甚至包括一个multi_array_ref可用于包装自己的一维数组缓冲区的类.
jus*_*tyy 24
为什么不使用STL:vector?这么简单,你不需要删除矢量.
int rows = 100;
int cols = 200;
vector< vector<int> > f(rows, vector<int>(cols));
f[rows - 1][cols - 1] = 0; // use it like arrays
Run Code Online (Sandbox Code Playgroud)
aks*_*har 15
2D数组基本上是一维指针数组,其中每个指针指向一维数组,该数组将保存实际数据.
这里N是行,M是列.
动态分配
int** ary = new int*[N];
for(int i = 0; i < N; i++)
ary[i] = new int[M];
Run Code Online (Sandbox Code Playgroud)
填
for(int i = 0; i < N; i++)
for(int j = 0; j < M; j++)
ary[i][j] = i;
Run Code Online (Sandbox Code Playgroud)
打印
for(int i = 0; i < N; i++)
for(int j = 0; j < M; j++)
std::cout << ary[i][j] << "\n";
Run Code Online (Sandbox Code Playgroud)
自由
for(int i = 0; i < N; i++)
delete [] ary[i];
delete [] ary;
Run Code Online (Sandbox Code Playgroud)
Rob*_*nes 14
typedef是你的朋友
回过头来看看其他许多答案后,我发现有更深层次的解释是正确的,因为许多其他答案要么遇到性能问题,要么强迫你使用不寻常或繁琐的语法来声明数组,或者访问数组元素(或以上所有).
首先,这个答案假定您在编译时知道数组的大小.如果这样做,那么这是最好的解决方案,因为它将提供最佳性能并允许您使用标准数组语法来访问数组元素.
这提供最佳性能的原因是因为它将所有数组分配为连续的内存块意味着您可能具有更少的页面未命中和更好的空间局部性.在循环中分配可能导致各个阵列最终分散在多个非连续页面上通过虚拟内存空间,因为分配循环可能被其他线程或进程中断(可能多次),或者仅仅由于其自行决定分配器填充小的空内存块,它恰好可用.
其他好处是简单的声明语法和标准数组访问语法.
在C++中使用new:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
typedef double (array5k_t)[5000];
array5k_t *array5k = new array5k_t[5000];
array5k[4999][4999] = 10;
printf("array5k[4999][4999] == %f\n", array5k[4999][4999]);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
或使用calloc的C风格:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
typedef double (*array5k_t)[5000];
array5k_t array5k = calloc(5000, sizeof(double)*5000);
array5k[4999][4999] = 10;
printf("array5k[4999][4999] == %f\n", array5k[4999][4999]);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
eth*_*ham 14
如何在GNU C++中分配连续的多维数组?有一个GNU扩展,允许"标准"语法工作.
似乎问题来自operator new [].确保使用operator new代替:
double (* in)[n][n] = new (double[m][n][n]); // GNU extension
Run Code Online (Sandbox Code Playgroud)
这就是全部:你得到一个C兼容的多维数组......
kam*_*shi 10
这个问题困扰了我15年,所提供的所有解决方案对我来说都不尽如人意.如何在内存中连续创建动态多维数组?今天我终于找到了答案.使用以下代码,您可以这样做:
#include <iostream>
int main(int argc, char** argv)
{
if (argc != 3)
{
std::cerr << "You have to specify the two array dimensions" << std::endl;
return -1;
}
int sizeX, sizeY;
sizeX = std::stoi(argv[1]);
sizeY = std::stoi(argv[2]);
if (sizeX <= 0)
{
std::cerr << "Invalid dimension x" << std::endl;
return -1;
}
if (sizeY <= 0)
{
std::cerr << "Invalid dimension y" << std::endl;
return -1;
}
/******** Create a two dimensional dynamic array in continuous memory ******
*
* - Define the pointer holding the array
* - Allocate memory for the array (linear)
* - Allocate memory for the pointers inside the array
* - Assign the pointers inside the array the corresponding addresses
* in the linear array
**************************************************************************/
// The resulting array
unsigned int** array2d;
// Linear memory allocation
unsigned int* temp = new unsigned int[sizeX * sizeY];
// These are the important steps:
// Allocate the pointers inside the array,
// which will be used to index the linear memory
array2d = new unsigned int*[sizeY];
// Let the pointers inside the array point to the correct memory addresses
for (int i = 0; i < sizeY; ++i)
{
array2d[i] = (temp + i * sizeX);
}
// Fill the array with ascending numbers
for (int y = 0; y < sizeY; ++y)
{
for (int x = 0; x < sizeX; ++x)
{
array2d[y][x] = x + y * sizeX;
}
}
// Code for testing
// Print the addresses
for (int y = 0; y < sizeY; ++y)
{
for (int x = 0; x < sizeX; ++x)
{
std::cout << std::hex << &(array2d[y][x]) << ' ';
}
}
std::cout << "\n\n";
// Print the array
for (int y = 0; y < sizeY; ++y)
{
std::cout << std::hex << &(array2d[y][0]) << std::dec;
std::cout << ": ";
for (int x = 0; x < sizeX; ++x)
{
std::cout << array2d[y][x] << ' ';
}
std::cout << std::endl;
}
// Free memory
delete[] array2d[0];
delete[] array2d;
array2d = nullptr;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当您使用值sizeX = 20和sizeY = 15调用程序时,输出将如下所示:
0x603010 0x603014 0x603018 0x60301c 0x603020 0x603024 0x603028 0x60302c 0x603030 0x603034 0x603038 0x60303c 0x603040 0x603044 0x603048 0x60304c 0x603050 0x603054 0x603058 0x60305c 0x603060 0x603064 0x603068 0x60306c 0x603070 0x603074 0x603078 0x60307c 0x603080 0x603084 0x603088 0x60308c 0x603090 0x603094 0x603098 0x60309c 0x6030a0 0x6030a4 0x6030a8 0x6030ac 0x6030b0 0x6030b4 0x6030b8 0x6030bc 0x6030c0 0x6030c4 0x6030c8 0x6030cc 0x6030d0 0x6030d4 0x6030d8 0x6030dc 0x6030e0 0x6030e4 0x6030e8 0x6030ec 0x6030f0 0x6030f4 0x6030f8 0x6030fc 0x603100 0x603104 0x603108 0x60310c 0x603110 0x603114 0x603118 0x60311c 0x603120 0x603124 0x603128 0x60312c 0x603130 0x603134 0x603138 0x60313c 0x603140 0x603144 0x603148 0x60314c 0x603150 0x603154 0x603158 0x60315c 0x603160 0x603164 0x603168 0x60316c 0x603170 0x603174 0x603178 0x60317c 0x603180 0x603184 0x603188 0x60318c 0x603190 0x603194 0x603198 0x60319c 0x6031a0 0x6031a4 0x6031a8 0x6031ac 0x6031b0 0x6031b4 0x6031b8 0x6031bc 0x6031c0 0x6031c4 0x6031c8 0x6031cc 0x6031d0 0x6031d4 0x6031d8 0x6031dc 0x6031e0 0x6031e4 0x6031e8 0x6031ec 0x6031f0 0x6031f4 0x6031f8 0x6031fc 0x603200 0x603204 0x603208 0x60320c 0x603210 0x603214 0x603218 0x60321c 0x603220 0x603224 0x603228 0x60322c 0x603230 0x603234 0x603238 0x60323c 0x603240 0x603244 0x603248 0x60324c 0x603250 0x603254 0x603258 0x60325c 0x603260 0x603264 0x603268 0x60326c 0x603270 0x603274 0x603278 0x60327c 0x603280 0x603284 0x603288 0x60328c 0x603290 0x603294 0x603298 0x60329c 0x6032a0 0x6032a4 0x6032a8 0x6032ac 0x6032b0 0x6032b4 0x6032b8 0x6032bc 0x6032c0 0x6032c4 0x6032c8 0x6032cc 0x6032d0 0x6032d4 0x6032d8 0x6032dc 0x6032e0 0x6032e4 0x6032e8 0x6032ec 0x6032f0 0x6032f4 0x6032f8 0x6032fc 0x603300 0x603304 0x603308 0x60330c 0x603310 0x603314 0x603318 0x60331c 0x603320 0x603324 0x603328 0x60332c 0x603330 0x603334 0x603338 0x60333c 0x603340 0x603344 0x603348 0x60334c 0x603350 0x603354 0x603358 0x60335c 0x603360 0x603364 0x603368 0x60336c 0x603370 0x603374 0x603378 0x60337c 0x603380 0x603384 0x603388 0x60338c 0x603390 0x603394 0x603398 0x60339c 0x6033a0 0x6033a4 0x6033a8 0x6033ac 0x6033b0 0x6033b4 0x6033b8 0x6033bc 0x6033c0 0x6033c4 0x6033c8 0x6033cc 0x6033d0 0x6033d4 0x6033d8 0x6033dc 0x6033e0 0x6033e4 0x6033e8 0x6033ec 0x6033f0 0x6033f4 0x6033f8 0x6033fc 0x603400 0x603404 0x603408 0x60340c 0x603410 0x603414 0x603418 0x60341c 0x603420 0x603424 0x603428 0x60342c 0x603430 0x603434 0x603438 0x60343c 0x603440 0x603444 0x603448 0x60344c 0x603450 0x603454 0x603458 0x60345c 0x603460 0x603464 0x603468 0x60346c 0x603470 0x603474 0x603478 0x60347c 0x603480 0x603484 0x603488 0x60348c 0x603490 0x603494 0x603498 0x60349c 0x6034a0 0x6034a4 0x6034a8 0x6034ac 0x6034b0 0x6034b4 0x6034b8 0x6034bc
0x603010: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
0x603060: 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
0x6030b0: 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
0x603100: 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
0x603150: 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
0x6031a0: 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
0x6031f0: 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
0x603240: 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
0x603290: 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
0x6032e0: 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
0x603330: 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
0x603380: 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
0x6033d0: 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
0x603420: 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
0x603470: 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
Run Code Online (Sandbox Code Playgroud)
如您所见,多维数组在内存中是连续的,并且没有两个内存地址重叠.即使释放数组的例程也比为每个列(或行,根据您查看数组的方式)动态分配内存的标准方法更简单.由于阵列基本上由两个线性阵列组成,因此只有这两个必须(并且可以)被释放.
该方法可以使用相同的概念扩展到两个以上的维度.我不会在这里做,但是当你了解它背后的想法时,这是一个简单的任务.
我希望这段代码可以帮助你,就像它帮助了我一样.
此答案的目的不是添加其他人尚未涵盖的任何新内容,而是扩展 @Kevin Loney 的答案。
您可以使用轻量级声明:
int *ary = new int[SizeX*SizeY]
Run Code Online (Sandbox Code Playgroud)
和访问语法将是:
ary[i*SizeY+j] // ary[i][j]
Run Code Online (Sandbox Code Playgroud)
但这对大多数人来说很麻烦,并可能导致混乱。因此,您可以按如下方式定义宏:
#define ary(i, j) ary[(i)*SizeY + (j)]
Run Code Online (Sandbox Code Playgroud)
现在您可以使用非常相似的语法访问数组ary(i, j) // means ary[i][j]。这样做的优点是简单美观,同时用表达式代替索引也更简单,更不容易混淆。
要访问,例如,ary[2+5][3+8],您可以编写ary(2+5, 3+8)而不是复杂的外观,ary[(2+5)*SizeY + (3+8)]即它节省了括号并有助于可读性。
注意事项:
SizeY则必须以相同的名称传递(或改为声明为全局变量)。或者,如果您需要在多个函数中使用数组,那么您也可以将 SizeY 添加为宏定义中的另一个参数,如下所示:
#define ary(i, j, SizeY) ary[(i)*(SizeY)+(j)]
Run Code Online (Sandbox Code Playgroud)
你明白了。当然,这会变得太长而无用,但它仍然可以防止 + 和 * 的混淆。
这不是绝对推荐的,大多数有经验的用户都会谴责它是不好的做法,但我忍不住分享它,因为它很优雅。
编辑:
如果您想要一个适用于任意数量数组的便携式解决方案,您可以使用以下语法:
#define access(ar, i, j, SizeY) ar[(i)*(SizeY)+(j)]
Run Code Online (Sandbox Code Playgroud)
然后你可以使用访问语法将任何数组传递给调用,任何大小:
access(ary, i, j, SizeY) // ary[i][j]
Run Code Online (Sandbox Code Playgroud)
PS:我已经测试过这些,并且相同的语法在 g++14 和 g++11 编译器上工作(作为左值和右值)。
尝试这样做:
int **ary = new int* [sizeY];
for (int i = 0; i < sizeY; i++)
ary[i] = new int[sizeX];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
869675 次 |
| 最近记录: |