How do i declare a 2d array using new?
如何使用new声明一个2d数组?
Like, for a "normal" array I would:
比如,对于一个“正常”数组,我将:
int* ary = new int[Size]
but
但
int** ary = new int[sizeY][sizeX]
a) doesn't work/compile and b) doesn't accomplish what:
a)不工作/编译和b)没有完成:
int ary[sizeY][sizeX]
does.
所做的事。
21 个解决方案
#1
578
A dynamic 2D array is basically an array of pointers to arrays. You can initialize it using a loop, like this:
动态2D数组基本上是数组的指针数组。您可以使用一个循环来初始化它:
int** a = new int*[rowCount];
for(int i = 0; i < rowCount; ++i)
a[i] = new int[colCount];
The above, for colCount= 5
and rowCount = 4
, would produce the following:
上面的colCount= 5和rowCount = 4将生成以下内容:
#2
262
int** ary = new int[sizeY][sizeX]
should be:
应该是:
int **ary = new int*[sizeY];
for(int i = 0; i < sizeY; ++i) {
ary[i] = new int[sizeX];
}
and then clean up would be:
然后清理一下
for(int i = 0; i < sizeY; ++i) {
delete [] ary[i];
}
delete [] ary;
EDIT: as Dietrich Epp pointed out in the comments this is not exactly a light weight solution. An alternative approach would be to use one large block of memory:
编辑:正如Dietrich Epp在评论中指出的那样,这并不是一个轻量级的解决方案。另一种方法是使用一大块内存:
int *ary = new int[sizeX*sizeY];
// ary[i][j] is then rewritten as
ary[i*sizeY+j]
#3
141
Although this popular answer will give you your desired indexing syntax, it is doubly inefficient: big and slow both in space and time. There's a better way.
虽然这个流行的答案会给出你想要的索引语法,但是它的效率非常低:在空间和时间上都是大而慢的。有一个更好的方法。
Why That Answer is Big and Slow
为什么这个答案又大又慢?
The proposed solution is to create a dynamic array of pointers, then initializing each pointer to its own, independent dynamic array. The advantage of this approach is that it gives you the indexing syntax you're used to, so if you want to find the value of the matrix at position x,y, you say:
建议的解决方案是创建一个指针的动态数组,然后将每个指针初始化为独立的动态数组。这种方法的优点是它提供了你所习惯的索引语法,所以如果你想要找到矩阵在位置x的值,y,你说:
int val = matrix[ x ][ y ];
This works because matrix[x] returns a pointer to an array, which is then indexed with [y]. Breaking it down:
这是可行的,因为矩阵[x]返回一个指向数组的指针,然后将其与[y]进行索引。分解:
int* row = matrix[ x ];
int val = row[ y ];
Convenient, yes? We like our [ x ][ y ] syntax.
方便,是吗?我们喜欢我们的[x][y]语法。
But the solution has a big disadvantage, which is that it is both fat and slow.
但是解决方案有一个很大的缺点,那就是它既胖又慢。
Why?
为什么?
The reason that it's both fat and slow is actually the same. Each "row" in the matrix is a separately allocated dynamic array. Making a heap allocation is expensive both in time and space. The allocator takes time to make the allocation, sometimes running O(n) algorithms to do it. And the allocator "pads" each of your row arrays with extra bytes for bookkeeping and alignment. That extra space costs...well...extra space. The deallocator will also take extra time when you go to deallocate the matrix, painstakingly free-ing up each individual row allocation. Gets me in a sweat just thinking about it.
它既胖又慢的原因其实是一样的。矩阵中的每个“行”是一个单独分配的动态数组。堆分配在时间和空间上都很昂贵。分配器需要时间来进行分配,有时运行O(n)算法来完成分配。并且分配器“pad”每个行数组都有额外的字节来进行簿记和对齐。额外的空间成本…额外的空间。当你去deallocate这个矩阵的时候,这个deallocator也会花费额外的时间,煞费苦心地让每一个单独的行分配。想想看,让我汗流浃背。
There's another reason it's slow. These separate allocations tend to live in discontinuous parts of memory. One row may be at address 1,000, another at address 100,000—you get the idea. This means that when you're traversing the matrix, you're leaping through memory like a wild person. This tends to result in cache misses that vastly slow down your processing time.
还有另一个原因,那就是慢。这些分开的分配倾向于生活在记忆的不连续部分。一排可能在1000,另一排在10万,你明白了。这意味着当你在穿越母体时,你像一个野人一样在记忆中跳跃。这会导致缓存丢失,从而大大降低处理时间。
So, if you absolute must have your cute [x][y] indexing syntax, use that solution. If you want quickness and smallness (and if you don't care about those, why are you working in C++?), you need a different solution.
因此,如果绝对必须有您可爱的[x][y]索引语法,请使用该解决方案。如果您想要快速和小(如果您不关心这些,为什么要在c++中工作?),您需要一个不同的解决方案。
A Different Solution
一个不同的解决方案
The better solution is to allocate your whole matrix as a single dynamic array, then use (slightly) clever indexing math of your own to access cells. The indexing math is only very slightly clever; nah, it's not clever at all: it's obvious.
更好的解决方案是将您的整个矩阵分配为单个动态数组,然后使用(稍微)巧妙的索引您自己的索引来访问单元格。索引数学只是非常聪明;不,一点也不聪明:很明显。
class Matrix
{
...
size_t index( int x, int y ) const { return x + m_width * y; }
};
Given this index()
function (which I'm imagining is a member of a class because it needs to know the m_width
of your matrix), you can access cells within your matrix array. The matrix array is allocated like this:
给定这个索引()函数(我想象它是一个类的成员,因为它需要知道您的矩阵的m_width),您可以访问矩阵数组中的单元格。矩阵数组是这样分配的:
array = new int[ width * height ];
So the equivalent of this in the slow, fat solution:
所以在缓慢的,脂肪的溶液中
array[ x ][ y ]
...is this in the quick, small solution:
…这是在快速,小的解决方案:
array[ index( x, y )]
Sad, I know. But you'll get used to it. And your CPU will thank you.
难过的时候,我知道。但你会习惯的。你的CPU会感谢你的。
#4
88
In C++11 it is possible:
在c++ 11中,这是可能的:
auto array = new double[M][N];
This way, the memory is not initialized. To initialize it do this instead:
这样,内存就不会被初始化。要初始化它,可以这样做:
auto array = new double[M][N]();
Sample program (compile with "g++ -std=c++11"):
样本程序(用“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;
}
Output:
输出:
2 4
3 5
0 0
0 0
double (*) [2]
#5
46
I presume from your static array example that you want a rectangular array, and not a jagged one. You can use the following:
我想,从静态数组的例子中,你需要一个矩形数组,而不是一个锯齿状数组。你可以使用以下方法:
int *ary = new int[sizeX * sizeY];
Then you can access elements as:
然后你可以访问元素:
ary[y*sizeX + x]
Don't forget to use delete[] on ary
.
不要忘记在ary上使用delete[]。
#6
30
There are two general techniques that I would recommend for this in C++11 and above, one for compile time dimensions and one for run time. Both answers assume you want uniform, two-dimensional arrays (not jagged ones).
我将在c++ 11和以上版本中推荐两种通用技术,一种用于编译时维,另一种用于运行时。这两个答案都假设您需要均匀的二维数组(而不是锯齿状的数组)。
Compile time dimensions
Use a std::array
of std::array
and then use new
to put it on the heap:
使用std:: std::数组,然后使用new将其放到堆上:
// the alias helps cut down on the noise:
using grid = std::array<std::array<int, sizeX> sizeY>;
grid * ary = new grid;
Again, this only works if the sizes of the dimensions are known at compile time.
同样,只有在编译时已知维度的大小时才会这样做。
Run time dimensions
The best way to accomplish a 2 dimensional array with sizes only known at runtime is to wrap it into a class. The class will allocate a 1d array and then overload operator []
to provide indexing for the first dimension. This works because in C++ a 2D array is row-major:
完成一个只有在运行时才知道大小的二维数组的最好方法是将它封装到一个类中。该类将分配一个一维数组,然后重载运算符[]为第一个维度提供索引。这是因为在c++中,2D数组是行-专业的:
(Taken from http://eli.thegreenplace.net/2015/memory-layout-of-multi-dimensional-arrays/)
(来自http://eli.thegreenplace.net/2015/memory-layout-of-multi-dimensional-arrays/)
A contiguous sequence of memory is good for performance reasons and is also easy to clean up. Here's an example class that omits a lot of useful methods but shows the basic idea:
连续的内存序列对性能有好处,而且易于清理。这里有一个示例类,它省略了许多有用的方法,但是显示了基本的思想:
#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();
}
}
So we create an array with std::make_unique<int[]>(rows * columns)
entries. We overload operator []
which will index the row for us. It returns an int *
which can then be dereferenced as normal for the column. Note that make_unique
first ships in C++14 but you can polyfill it in C++11 if necessary.
因此,我们创建一个带有std::make_unique
It's also common for these types of structures to overload operator()
as well:
对于这些类型的结构,重载运算符()也很常见:
int & operator() (size_t row, size_t column) {
return data[row * _columns + column];
}
Technically I haven't used new
here, but it's trivial to move from std::unique_ptr<int[]>
to int *
and use new
/delete
.
从技术上讲,我还没有在这里使用new,但是从std::unique_ptr
#7
23
This question was bugging me - it's a common enough problem that a good solution should already exist, something better than the vector of vectors or rolling your own array indexing.
这个问题困扰着我——这是一个很常见的问题,一个好的解决方案应该已经存在,比向量的向量更好,或者滚动你自己的数组索引。
When something ought to exist in C++ but doesn't, the first place to look is boost.org. There I found the Boost Multidimensional Array Library, multi_array
. It even includes a multi_array_ref
class that can be used to wrap your own one-dimensional array buffer.
当某些东西应该存在于c++中时,首先要看的是boost.org。在那里我发现了Boost多维数组库,multi_array。它甚至包括一个multi_array_ref类,它可以用来包装您自己的一维数组缓冲区。
#8
19
Why not use STL:vector? So easy, and you don't need to delete the vector.
为什么不使用STL:向量?很简单,你不需要删除向量。
int rows = 100;
int cols = 200;
vector< vector<int> > f(rows, vector<int>(cols));
f[rows - 1][cols - 1] = 0; // use it like arrays
#9
12
How to allocate a contiguous multidimensional array in GNU C++? There's a GNU extension that allows the "standard" syntax to work.
如何在GNU c++中分配一个连续的多维数组?有一个GNU扩展允许“标准”语法工作。
It seems the problem come from operator new []. Make sure you use operator new instead :
问题似乎来自新运营商。请确保使用新的操作符:
double (* in)[n][n] = new (double[m][n][n]); // GNU extension
And that's all : you get a C-compatible multidimensional array...
这就是全部:你得到一个c兼容的多维数组…
#10
11
typedef is your friend
typedef是你的朋友
After going back and looking at many of the other answers I found that a deeper explanation is in order, as many of the other answers either suffer from performance problems or force you to use unusual or burdensome syntax to declare the array, or access the array elements ( or all the above ).
回去后,看着许多其他的答案我发现更深层次的解释是,尽可能多的其他答案遭受性能问题或强迫你使用不寻常或繁重的语法来声明数组,或访问数组元素(或以上)。
First off, this answer assumes you know the dimensions of the array at compile time. If you do, then this is the best solution as it will both give the best performance and allows you to use standard array syntax to access the array elements.
首先,这个答案假设您知道在编译时数组的大小。如果您这样做,那么这是最好的解决方案,因为它将提供最佳性能,并允许您使用标准数组语法访问数组元素。
The reason this gives the best performance is because it allocates all of the arrays as a contiguous block of memory meaning that you are likely to have less page misses and better spacial locality. Allocating in a loop may cause the individual arrays to end up scattered on multiple non-contiguous pages through the virtual memory space as the allocation loop could be interrupted ( possibly multiple times ) by other threads or processes, or simply due to the discretion of the allocator filling in small, empty memory blocks it happens to have available.
之所以给出最佳性能,是因为它将所有的数组分配为一个连续的内存块,这意味着您可能有更少的页面丢失和更好的空间位置。分配在一个循环中可能会导致个体数组最后分散在多个不连续的页面通过虚拟内存空间的分配循环可以中断(可能多次)由其他线程或进程,或者仅仅是由于*裁量权的分配程序填写小,空的内存块可用。
The other benefits are a simple declaration syntax and standard array access syntax.
另一个好处是简单的声明语法和标准的数组访问语法。
In C++ using new:
在c++中使用新的:
#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;
}
Or C style using calloc:
或C风格使用calloc:
#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;
}
#11
11
A 2D array is basically a 1D array of pointers, where every pointer is pointing to a 1D array, which will hold the actual data.
2D数组基本上是一个指针的一维数组,每个指针指向一个一维数组,该数组将保存实际的数据。
Here N is row and M is column.
这里N是行,M是列。
dynamic allocation
动态分配
int** ary = new int*[N];
for(int i = 0; i < N; i++)
ary[i] = new int[M];
fill
填满
for(int i = 0; i < N; i++)
for(int j = 0; j < M; j++)
ary[i][j] = i;
打印
for(int i = 0; i < N; i++)
for(int j = 0; j < M; j++)
std::cout << ary[i][j] << "\n";
free
免费的
for(int i = 0; i < N; i++)
delete [] ary[i];
or
或
delete [] ary;
#12
7
Try doing this:
试着这样做:
int **ary = new int[sizeY];
for (int i = 0; i < sizeY; i++)
ary[i] = new int[sizeX];
#13
7
This problem has bothered me for 15 years, and all the solutions supplied weren't satisfactory for me. How do you create a dynamic multidimensional array contiguously in memory. Today I finally found the answer. Using the following code, you can do just that:
这个问题困扰了我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;
}
When you invoke the program with the values sizeX=20 and sizeY=15, the output will be the following:
当您使用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
As you can see, the multidimensional array lies contiguously in memory, and no two memory addresses are overlapping. Even the routine for freeing the array is simpler than the standard way of dynamically allocating memory for every single column (or row, depending on how you view the array). Since the array basically consists of two linear arrays, only these two have to be (and can be) freed.
如您所见,多维数组在内存中是连续的,没有两个内存地址重叠。即使是用于释放数组的例程,也比动态分配每个列(或行,取决于您如何查看数组)的标准方法更简单。由于数组基本上由两个线性数组组成,所以只有这两个数组必须(并且可以)被释放。
This method can be extended for more than two dimensions with the same concept. I won't do it here, but when you get the idea behind it, it is a simple task.
这种方法可以用相同的概念扩展到两个以上的维度。我不会在这里做,但是当你有了这个想法后,这是一个简单的任务。
I hope this code will help you as much as it helped me.
我希望这段代码能对你有所帮助。
#14
2
Start by defining the array using pointers (Line 1):
首先使用指针定义数组(第1行):
int** a = new int* [x]; //x is the number of rows
for(int i = 0; i < x; i++)
a[i] = new int[y]; //y is the number of columns
#15
2
Here, I have two options. The first one shows the concept of an array of arrays or pointer of pointers. I prefer the second one because the addresses are contiguous, as you can see in the image.
这里,我有两个选择。第一个显示了数组数组或指针指针的概念。我喜欢第二个,因为地址是连续的,就像你在图片中看到的那样。
#include <iostream>
using namespace std;
int main(){
int **arr_01,**arr_02,i,j,rows=4,cols=5;
//Implementation 1
arr_01=new int*[rows];
for(int i=0;i<rows;i++)
arr_01[i]=new int[cols];
for(i=0;i<rows;i++){
for(j=0;j<cols;j++)
cout << arr_01[i]+j << " " ;
cout << endl;
}
for(int i=0;i<rows;i++)
delete[] arr_01[i];
delete[] arr_01;
cout << endl;
//Implementation 2
arr_02=new int*[rows];
arr_02[0]=new int[rows*cols];
for(int i=1;i<rows;i++)
arr_02[i]=arr_02[0]+cols*i;
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++)
cout << arr_02[i]+j << " " ;
cout << endl;
}
delete[] arr_02[0];
delete[] arr_02;
return 0;
}
#16
1
If your project is CLI (Common Language Runtime Support), then:
如果您的项目是CLI(公共语言运行时支持),那么:
You can use the array class, not that one you get when you write:
你可以使用数组类,而不是你写的那个
#include <array>
using namespace std;
In other words, not the unmanaged array class you get when using the std namespace and when including the array header, not the unmanaged array class defined in the std namespace and in the array header, but the managed class array of the CLI.
换句话说,不是在使用std名称空间时得到的非托管数组类,在包括数组头的时候,不是在std名称空间中定义的非托管数组类和在数组头中定义的非托管数组类,而是CLI的托管类数组。
with this class, you can create an array of any rank you want.
使用这个类,您可以创建任意级别的数组。
The following code below creates new two dimensional array of 2 rows and 3 columns and of type int, and I name it "arr":
下面的代码创建了2行和3列的新二维数组,以及类型int,我将其命名为“arr”:
array<int, 2>^ arr = gcnew array<int, 2>(2, 3);
Now you can access elements in the array, by name it and write only one squared parentheses []
, and inside them, add the row and column, and separate them with the comma ,
.
现在您可以访问数组中的元素,通过名称和只写一个方括号[],在其中添加行和列,并将它们与逗号分开。
The following code below access an element in 2nd row and 1st column of the array I already created in previous code above:
下面的代码访问了前面代码中已经创建的数组的第2行和第1列中的元素:
arr[0, 1]
writing only this line is to read the value in that cell, i.e. get the value in this cell, but if you add the equal =
sign, you are about to write the value in that cell, i.e. set the value in this cell. You also can use the +=, -=, *= and /= operators of course, for numbers only (int, float, double, __int16, __int32, __int64 and etc), but sure you know it already.
只写这一行,就是读取该单元格中的值,即获取该单元格中的值,但如果添加等号,则将写入该单元格中的值,即设置该单元格中的值。您还可以使用+=、-=、*=和/=操作符,仅对数字(int、float、double、__int16、__int32、__int64等),但您肯定已经知道了。
If your project is not CLI, then you can use the unmanaged array class of the std namespace, if you #include <array>
, of course, but the problem is that this array class is different than the CLI array. Create array of this type is same like the CLI, except that you will have to remove the ^
sign and the gcnew
keyword. But unfortunately the second int parameter in the <>
parentheses specifies the length (i.e. size) of the array, not its rank!
如果您的项目不是CLI,那么您可以使用std名称空间的非托管数组类,如果您包括
There is no way to specify rank in this kind of array, rank is CLI array's feature only..
在这种数组中没有指定rank的方法,rank是CLI数组的特性。
std array behaves like normal array in c++, that you define with pointer, for example int*
and then: new int[size]
, or without pointer: int arr[size]
, but unlike the normal array of the c++, std array provides functions that you can use with the elements of the array, like fill, begin, end, size, and etc, but normal array provides nothing.
性病阵列像正常的数组在c++中,您定义的指针,例如int *然后:新int(大小),或没有指针:int arr(大小),但与正常的c++数组,性病数组提供功能,您可以使用数组的元素,像填满,开始,结束,大小等,但正常的阵列提供了什么。
But still std array are one dimensional array, like the normal c++ arrays. But thanks to the solutions that the other guys suggest about how you can make the normal c++ one dimensional array to two dimensional array, we can adapt the same ideas to std array, e.g. according to Mehrdad Afshari's idea, we can write the following code:
但是std数组仍然是一维数组,就像普通的c++数组一样。但是由于其他的解决方案,其他的人建议如何使普通的c++一维数组到二维数组,我们可以将相同的想法应用到std阵列中,例如根据Mehrdad Afshari的想法,我们可以编写如下代码:
array<array<int, 3>, 2> array2d = array<array<int, 3>, 2>();
This line of code creates a "jugged array", which is an one dimensional array that each of its cells is or points to another one dimensional array.
这行代码创建了一个“jugged array”,它是一个一维数组,每个单元格都是或指向另一个一维数组。
If all one dimensional arrays in one dimensional array are equal in their length/size, then you can treat the array2d variable as a real two dimensional array, plus you can use the special methods to treat rows or columns, depends on how you view it in mind, in the 2D array, that std array supports.
如果所有的一维数组,一维数组长度/尺寸是相等的,那么你可以把array2d变量当作一个真正的二维数组,以及您可以使用特殊的方法来治疗行或列,取决于你如何看待它,性病的二维数组,数组的支持。
You also can use Kevin Loney's solution:
你也可以使用Kevin Loney的解决方案:
int *ary = new int[sizeX*sizeY];
// ary[i][j] is then rewritten as
ary[i*sizeY+j]
but if you use std array, the code must look different:
但是如果使用std数组,代码必须看起来不同:
array<int, sizeX*sizeY> ary = array<int, sizeX*sizeY>();
ary.at(i*sizeY+j);
And still have the unique functions of the std array.
还有std阵列的独特功能。
Note that you still can access the elements of the std array using the []
parentheses, and you don't have to call the at
function. You also can define and assign new int variable that will calculate and keep the total number of elements in the std array, and use its value, instead of repeating sizeX*sizeY
注意,您仍然可以使用[]括号访问std数组的元素,并且您不必调用at函数。您还可以定义和分配新的int变量,该变量将计算并保留std数组中元素的总数,并使用其值,而不是重复sizeX*sizeY。
You can define your own two dimensional array generic class, and define the constructor of the two dimensional array class to receive two integers to specify the number of rows and columns in the new two dimensional array, and define get function that receive two parameters of integer that access an element in the two dimensional array and returns its value, and set function that receives three parameters, that the two first are integers that specify the row and column in the two dimensional array, and the third parameter is the new value of the element. Its type depends on the type you chose in the generic class.
您可以定义您自己的二维数组泛型类,并定义二维数组类的构造函数接受两个整数指定的行数和列的二维数组,并定义函数接受两个参数的整数,访问二维数组中的一个元素,并返回它的值,并设置函数接受三个参数,一分之二是整数指定行和列的二维数组,和第三个参数是元素的新值。它的类型取决于您在泛型类中选择的类型。
You will be able to implement all this by using either the normal c++ array (pointers or without) or the std array and use one of the ideas that other people suggested, and make it easy to use like the cli array, or like the two dimensional array that you can define, assign and use in C#.
你将能够实现所有通过正常使用c++数组指针(或没有)或性病数组和使用的一个想法别人建议,并使其易于使用和cli数组一样,或者像二维数组,您可以定义、分配和在c#中使用。
#17
1
I have left you with a solution which works the best for me, in certain cases. Especially if one knows [the size of?] one dimension of the array. Very useful for an array of chars, for instance if we need an array of varying size of arrays of char[20].
在某些情况下,我给了你一个最适合我的解决方案。特别是如果你知道(尺寸)]数组的一维。对于一个字符数组非常有用,例如,如果我们需要一个字符数组大小不等的数组[20]。
int size = 1492;
char (*array)[20];
array = new char[size][20];
...
strcpy(array[5], "hola!");
...
delete [] array;
The key is the parentheses in the array declaration.
关键是数组声明中的圆括号。
#18
1
I used this not elegant but FAST,EASY and WORKING system. I do not see why can not work because the only way for the system to allow create a big size array and access parts is without cutting it in parts:
我用的不是优雅,而是快速,简单和工作的系统。我不明白为什么不能工作,因为系统允许创建一个大尺寸数组和访问部件的唯一方法是不把它分割成部分:
#define DIM 3
#define WORMS 50000 //gusanos
void halla_centros_V000(double CENW[][DIM])
{
CENW[i][j]=...
...
}
int main()
{
double *CENW_MEM=new double[WORMS*DIM];
double (*CENW)[DIM];
CENW=(double (*)[3]) &CENW_MEM[0];
halla_centros_V000(CENW);
delete[] CENW_MEM;
}
#19
-1
declaring 2D array dynamically:
声明动态二维数组:
#include<iostream>
using namespace std;
int main()
{
int x = 3, y = 3;
int **ptr = new int *[x];
for(int i = 0; i<y; i++)
{
ptr[i] = new int[y];
}
srand(time(0));
for(int j = 0; j<x; j++)
{
for(int k = 0; k<y; k++)
{
int a = rand()%10;
ptr[j][k] = a;
cout<<ptr[j][k]<<" ";
}
cout<<endl;
}
}
Now in the above code we took a double pointer and assigned it a dynamic memory and gave a value of the columns. Here the memory allocated is only for the columns, now for the rows we just need a for loop and assign the value for every row a dynamic memory. Now we can use the pointer just the way we use a 2D array. In the above example we then assigned random numbers to our 2D array(pointer).Its all about DMA of 2D array.
在上面的代码中,我们使用了一个双指针并赋予它一个动态内存并给出了列的值。这里分配的内存仅用于列,现在对于行,我们只需要一个for循环,并为每个行分配一个动态内存的值。现在我们可以使用指针,就像我们使用2D数组一样。在上面的示例中,我们将随机数分配给我们的2D数组(指针)。它的全部关于DMA的二维数组。
#20
-1
I'm using this when creating dynamic array. If you have a class or a struct. And this works. Example:
我在创建动态数组时使用这个。如果你有一个类或结构。这工作。例子:
struct Sprite {
int x;
};
int main () {
int num = 50;
Sprite **spritearray;//a pointer to a pointer to an object from the Sprite class
spritearray = new Sprite *[num];
for (int n = 0; n < num; n++) {
spritearray[n] = new Sprite;
spritearray->x = n * 3;
}
//delete from random position
for (int n = 0; n < num; n++) {
if (spritearray[n]->x < 0) {
delete spritearray[n];
spritearray[n] = NULL;
}
}
//delete the array
for (int n = 0; n < num; n++) {
if (spritearray[n] != NULL){
delete spritearray[n];
spritearray[n] = NULL;
}
}
delete []spritearray;
spritearray = NULL;
return 0;
}
#21
-1
This is not the one in much details, but quite simplified.
这不是很多细节中的一个,但是非常简单。
int *arrayPointer = new int[4][5][6]; // ** LEGAL**
int *arrayPointer = new int[m][5][6]; // ** LEGAL** m will be calculated at run time
int *arrayPointer = new int[3][5][]; // ** ILLEGAL **, No index can be empty
int *arrayPointer = new int[][5][6]; // ** ILLEGAL **, No index can be empty
Remember:
记住:
1. ONLY THE THE FIRST INDEX CAN BE A RUNTIME VARIABLE. OTHER INDEXES NEED TO BE CONSTANT
1。只有第一个索引可以是一个运行时变量。其他指标需要保持不变。
2. NO INDEX CAN BE LEFT EMPTY.
2。索引不能空。
As mentioned in other answers, call
如其他答案所述,请打电话。
delete arrayPointer;
to deallocate memory associated with the array when you are done with the array.
当您完成数组时,将与数组关联的内存分配。
#1
578
A dynamic 2D array is basically an array of pointers to arrays. You can initialize it using a loop, like this:
动态2D数组基本上是数组的指针数组。您可以使用一个循环来初始化它:
int** a = new int*[rowCount];
for(int i = 0; i < rowCount; ++i)
a[i] = new int[colCount];
The above, for colCount= 5
and rowCount = 4
, would produce the following:
上面的colCount= 5和rowCount = 4将生成以下内容:
#2
262
int** ary = new int[sizeY][sizeX]
should be:
应该是:
int **ary = new int*[sizeY];
for(int i = 0; i < sizeY; ++i) {
ary[i] = new int[sizeX];
}
and then clean up would be:
然后清理一下
for(int i = 0; i < sizeY; ++i) {
delete [] ary[i];
}
delete [] ary;
EDIT: as Dietrich Epp pointed out in the comments this is not exactly a light weight solution. An alternative approach would be to use one large block of memory:
编辑:正如Dietrich Epp在评论中指出的那样,这并不是一个轻量级的解决方案。另一种方法是使用一大块内存:
int *ary = new int[sizeX*sizeY];
// ary[i][j] is then rewritten as
ary[i*sizeY+j]
#3
141
Although this popular answer will give you your desired indexing syntax, it is doubly inefficient: big and slow both in space and time. There's a better way.
虽然这个流行的答案会给出你想要的索引语法,但是它的效率非常低:在空间和时间上都是大而慢的。有一个更好的方法。
Why That Answer is Big and Slow
为什么这个答案又大又慢?
The proposed solution is to create a dynamic array of pointers, then initializing each pointer to its own, independent dynamic array. The advantage of this approach is that it gives you the indexing syntax you're used to, so if you want to find the value of the matrix at position x,y, you say:
建议的解决方案是创建一个指针的动态数组,然后将每个指针初始化为独立的动态数组。这种方法的优点是它提供了你所习惯的索引语法,所以如果你想要找到矩阵在位置x的值,y,你说:
int val = matrix[ x ][ y ];
This works because matrix[x] returns a pointer to an array, which is then indexed with [y]. Breaking it down:
这是可行的,因为矩阵[x]返回一个指向数组的指针,然后将其与[y]进行索引。分解:
int* row = matrix[ x ];
int val = row[ y ];
Convenient, yes? We like our [ x ][ y ] syntax.
方便,是吗?我们喜欢我们的[x][y]语法。
But the solution has a big disadvantage, which is that it is both fat and slow.
但是解决方案有一个很大的缺点,那就是它既胖又慢。
Why?
为什么?
The reason that it's both fat and slow is actually the same. Each "row" in the matrix is a separately allocated dynamic array. Making a heap allocation is expensive both in time and space. The allocator takes time to make the allocation, sometimes running O(n) algorithms to do it. And the allocator "pads" each of your row arrays with extra bytes for bookkeeping and alignment. That extra space costs...well...extra space. The deallocator will also take extra time when you go to deallocate the matrix, painstakingly free-ing up each individual row allocation. Gets me in a sweat just thinking about it.
它既胖又慢的原因其实是一样的。矩阵中的每个“行”是一个单独分配的动态数组。堆分配在时间和空间上都很昂贵。分配器需要时间来进行分配,有时运行O(n)算法来完成分配。并且分配器“pad”每个行数组都有额外的字节来进行簿记和对齐。额外的空间成本…额外的空间。当你去deallocate这个矩阵的时候,这个deallocator也会花费额外的时间,煞费苦心地让每一个单独的行分配。想想看,让我汗流浃背。
There's another reason it's slow. These separate allocations tend to live in discontinuous parts of memory. One row may be at address 1,000, another at address 100,000—you get the idea. This means that when you're traversing the matrix, you're leaping through memory like a wild person. This tends to result in cache misses that vastly slow down your processing time.
还有另一个原因,那就是慢。这些分开的分配倾向于生活在记忆的不连续部分。一排可能在1000,另一排在10万,你明白了。这意味着当你在穿越母体时,你像一个野人一样在记忆中跳跃。这会导致缓存丢失,从而大大降低处理时间。
So, if you absolute must have your cute [x][y] indexing syntax, use that solution. If you want quickness and smallness (and if you don't care about those, why are you working in C++?), you need a different solution.
因此,如果绝对必须有您可爱的[x][y]索引语法,请使用该解决方案。如果您想要快速和小(如果您不关心这些,为什么要在c++中工作?),您需要一个不同的解决方案。
A Different Solution
一个不同的解决方案
The better solution is to allocate your whole matrix as a single dynamic array, then use (slightly) clever indexing math of your own to access cells. The indexing math is only very slightly clever; nah, it's not clever at all: it's obvious.
更好的解决方案是将您的整个矩阵分配为单个动态数组,然后使用(稍微)巧妙的索引您自己的索引来访问单元格。索引数学只是非常聪明;不,一点也不聪明:很明显。
class Matrix
{
...
size_t index( int x, int y ) const { return x + m_width * y; }
};
Given this index()
function (which I'm imagining is a member of a class because it needs to know the m_width
of your matrix), you can access cells within your matrix array. The matrix array is allocated like this:
给定这个索引()函数(我想象它是一个类的成员,因为它需要知道您的矩阵的m_width),您可以访问矩阵数组中的单元格。矩阵数组是这样分配的:
array = new int[ width * height ];
So the equivalent of this in the slow, fat solution:
所以在缓慢的,脂肪的溶液中
array[ x ][ y ]
...is this in the quick, small solution:
…这是在快速,小的解决方案:
array[ index( x, y )]
Sad, I know. But you'll get used to it. And your CPU will thank you.
难过的时候,我知道。但你会习惯的。你的CPU会感谢你的。
#4
88
In C++11 it is possible:
在c++ 11中,这是可能的:
auto array = new double[M][N];
This way, the memory is not initialized. To initialize it do this instead:
这样,内存就不会被初始化。要初始化它,可以这样做:
auto array = new double[M][N]();
Sample program (compile with "g++ -std=c++11"):
样本程序(用“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;
}
Output:
输出:
2 4
3 5
0 0
0 0
double (*) [2]
#5
46
I presume from your static array example that you want a rectangular array, and not a jagged one. You can use the following:
我想,从静态数组的例子中,你需要一个矩形数组,而不是一个锯齿状数组。你可以使用以下方法:
int *ary = new int[sizeX * sizeY];
Then you can access elements as:
然后你可以访问元素:
ary[y*sizeX + x]
Don't forget to use delete[] on ary
.
不要忘记在ary上使用delete[]。
#6
30
There are two general techniques that I would recommend for this in C++11 and above, one for compile time dimensions and one for run time. Both answers assume you want uniform, two-dimensional arrays (not jagged ones).
我将在c++ 11和以上版本中推荐两种通用技术,一种用于编译时维,另一种用于运行时。这两个答案都假设您需要均匀的二维数组(而不是锯齿状的数组)。
Compile time dimensions
Use a std::array
of std::array
and then use new
to put it on the heap:
使用std:: std::数组,然后使用new将其放到堆上:
// the alias helps cut down on the noise:
using grid = std::array<std::array<int, sizeX> sizeY>;
grid * ary = new grid;
Again, this only works if the sizes of the dimensions are known at compile time.
同样,只有在编译时已知维度的大小时才会这样做。
Run time dimensions
The best way to accomplish a 2 dimensional array with sizes only known at runtime is to wrap it into a class. The class will allocate a 1d array and then overload operator []
to provide indexing for the first dimension. This works because in C++ a 2D array is row-major:
完成一个只有在运行时才知道大小的二维数组的最好方法是将它封装到一个类中。该类将分配一个一维数组,然后重载运算符[]为第一个维度提供索引。这是因为在c++中,2D数组是行-专业的:
(Taken from http://eli.thegreenplace.net/2015/memory-layout-of-multi-dimensional-arrays/)
(来自http://eli.thegreenplace.net/2015/memory-layout-of-multi-dimensional-arrays/)
A contiguous sequence of memory is good for performance reasons and is also easy to clean up. Here's an example class that omits a lot of useful methods but shows the basic idea:
连续的内存序列对性能有好处,而且易于清理。这里有一个示例类,它省略了许多有用的方法,但是显示了基本的思想:
#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();
}
}
So we create an array with std::make_unique<int[]>(rows * columns)
entries. We overload operator []
which will index the row for us. It returns an int *
which can then be dereferenced as normal for the column. Note that make_unique
first ships in C++14 but you can polyfill it in C++11 if necessary.
因此,我们创建一个带有std::make_unique
It's also common for these types of structures to overload operator()
as well:
对于这些类型的结构,重载运算符()也很常见:
int & operator() (size_t row, size_t column) {
return data[row * _columns + column];
}
Technically I haven't used new
here, but it's trivial to move from std::unique_ptr<int[]>
to int *
and use new
/delete
.
从技术上讲,我还没有在这里使用new,但是从std::unique_ptr
#7
23
This question was bugging me - it's a common enough problem that a good solution should already exist, something better than the vector of vectors or rolling your own array indexing.
这个问题困扰着我——这是一个很常见的问题,一个好的解决方案应该已经存在,比向量的向量更好,或者滚动你自己的数组索引。
When something ought to exist in C++ but doesn't, the first place to look is boost.org. There I found the Boost Multidimensional Array Library, multi_array
. It even includes a multi_array_ref
class that can be used to wrap your own one-dimensional array buffer.
当某些东西应该存在于c++中时,首先要看的是boost.org。在那里我发现了Boost多维数组库,multi_array。它甚至包括一个multi_array_ref类,它可以用来包装您自己的一维数组缓冲区。
#8
19
Why not use STL:vector? So easy, and you don't need to delete the vector.
为什么不使用STL:向量?很简单,你不需要删除向量。
int rows = 100;
int cols = 200;
vector< vector<int> > f(rows, vector<int>(cols));
f[rows - 1][cols - 1] = 0; // use it like arrays
#9
12
How to allocate a contiguous multidimensional array in GNU C++? There's a GNU extension that allows the "standard" syntax to work.
如何在GNU c++中分配一个连续的多维数组?有一个GNU扩展允许“标准”语法工作。
It seems the problem come from operator new []. Make sure you use operator new instead :
问题似乎来自新运营商。请确保使用新的操作符:
double (* in)[n][n] = new (double[m][n][n]); // GNU extension
And that's all : you get a C-compatible multidimensional array...
这就是全部:你得到一个c兼容的多维数组…
#10
11
typedef is your friend
typedef是你的朋友
After going back and looking at many of the other answers I found that a deeper explanation is in order, as many of the other answers either suffer from performance problems or force you to use unusual or burdensome syntax to declare the array, or access the array elements ( or all the above ).
回去后,看着许多其他的答案我发现更深层次的解释是,尽可能多的其他答案遭受性能问题或强迫你使用不寻常或繁重的语法来声明数组,或访问数组元素(或以上)。
First off, this answer assumes you know the dimensions of the array at compile time. If you do, then this is the best solution as it will both give the best performance and allows you to use standard array syntax to access the array elements.
首先,这个答案假设您知道在编译时数组的大小。如果您这样做,那么这是最好的解决方案,因为它将提供最佳性能,并允许您使用标准数组语法访问数组元素。
The reason this gives the best performance is because it allocates all of the arrays as a contiguous block of memory meaning that you are likely to have less page misses and better spacial locality. Allocating in a loop may cause the individual arrays to end up scattered on multiple non-contiguous pages through the virtual memory space as the allocation loop could be interrupted ( possibly multiple times ) by other threads or processes, or simply due to the discretion of the allocator filling in small, empty memory blocks it happens to have available.
之所以给出最佳性能,是因为它将所有的数组分配为一个连续的内存块,这意味着您可能有更少的页面丢失和更好的空间位置。分配在一个循环中可能会导致个体数组最后分散在多个不连续的页面通过虚拟内存空间的分配循环可以中断(可能多次)由其他线程或进程,或者仅仅是由于*裁量权的分配程序填写小,空的内存块可用。
The other benefits are a simple declaration syntax and standard array access syntax.
另一个好处是简单的声明语法和标准的数组访问语法。
In C++ using new:
在c++中使用新的:
#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;
}
Or C style using calloc:
或C风格使用calloc:
#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;
}
#11
11
A 2D array is basically a 1D array of pointers, where every pointer is pointing to a 1D array, which will hold the actual data.
2D数组基本上是一个指针的一维数组,每个指针指向一个一维数组,该数组将保存实际的数据。
Here N is row and M is column.
这里N是行,M是列。
dynamic allocation
动态分配
int** ary = new int*[N];
for(int i = 0; i < N; i++)
ary[i] = new int[M];
fill
填满
for(int i = 0; i < N; i++)
for(int j = 0; j < M; j++)
ary[i][j] = i;
打印
for(int i = 0; i < N; i++)
for(int j = 0; j < M; j++)
std::cout << ary[i][j] << "\n";
free
免费的
for(int i = 0; i < N; i++)
delete [] ary[i];
or
或
delete [] ary;
#12
7
Try doing this:
试着这样做:
int **ary = new int[sizeY];
for (int i = 0; i < sizeY; i++)
ary[i] = new int[sizeX];
#13
7
This problem has bothered me for 15 years, and all the solutions supplied weren't satisfactory for me. How do you create a dynamic multidimensional array contiguously in memory. Today I finally found the answer. Using the following code, you can do just that:
这个问题困扰了我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;
}
When you invoke the program with the values sizeX=20 and sizeY=15, the output will be the following:
当您使用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
As you can see, the multidimensional array lies contiguously in memory, and no two memory addresses are overlapping. Even the routine for freeing the array is simpler than the standard way of dynamically allocating memory for every single column (or row, depending on how you view the array). Since the array basically consists of two linear arrays, only these two have to be (and can be) freed.
如您所见,多维数组在内存中是连续的,没有两个内存地址重叠。即使是用于释放数组的例程,也比动态分配每个列(或行,取决于您如何查看数组)的标准方法更简单。由于数组基本上由两个线性数组组成,所以只有这两个数组必须(并且可以)被释放。
This method can be extended for more than two dimensions with the same concept. I won't do it here, but when you get the idea behind it, it is a simple task.
这种方法可以用相同的概念扩展到两个以上的维度。我不会在这里做,但是当你有了这个想法后,这是一个简单的任务。
I hope this code will help you as much as it helped me.
我希望这段代码能对你有所帮助。
#14
2
Start by defining the array using pointers (Line 1):
首先使用指针定义数组(第1行):
int** a = new int* [x]; //x is the number of rows
for(int i = 0; i < x; i++)
a[i] = new int[y]; //y is the number of columns
#15
2
Here, I have two options. The first one shows the concept of an array of arrays or pointer of pointers. I prefer the second one because the addresses are contiguous, as you can see in the image.
这里,我有两个选择。第一个显示了数组数组或指针指针的概念。我喜欢第二个,因为地址是连续的,就像你在图片中看到的那样。
#include <iostream>
using namespace std;
int main(){
int **arr_01,**arr_02,i,j,rows=4,cols=5;
//Implementation 1
arr_01=new int*[rows];
for(int i=0;i<rows;i++)
arr_01[i]=new int[cols];
for(i=0;i<rows;i++){
for(j=0;j<cols;j++)
cout << arr_01[i]+j << " " ;
cout << endl;
}
for(int i=0;i<rows;i++)
delete[] arr_01[i];
delete[] arr_01;
cout << endl;
//Implementation 2
arr_02=new int*[rows];
arr_02[0]=new int[rows*cols];
for(int i=1;i<rows;i++)
arr_02[i]=arr_02[0]+cols*i;
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++)
cout << arr_02[i]+j << " " ;
cout << endl;
}
delete[] arr_02[0];
delete[] arr_02;
return 0;
}
#16
1
If your project is CLI (Common Language Runtime Support), then:
如果您的项目是CLI(公共语言运行时支持),那么:
You can use the array class, not that one you get when you write:
你可以使用数组类,而不是你写的那个
#include <array>
using namespace std;
In other words, not the unmanaged array class you get when using the std namespace and when including the array header, not the unmanaged array class defined in the std namespace and in the array header, but the managed class array of the CLI.
换句话说,不是在使用std名称空间时得到的非托管数组类,在包括数组头的时候,不是在std名称空间中定义的非托管数组类和在数组头中定义的非托管数组类,而是CLI的托管类数组。
with this class, you can create an array of any rank you want.
使用这个类,您可以创建任意级别的数组。
The following code below creates new two dimensional array of 2 rows and 3 columns and of type int, and I name it "arr":
下面的代码创建了2行和3列的新二维数组,以及类型int,我将其命名为“arr”:
array<int, 2>^ arr = gcnew array<int, 2>(2, 3);
Now you can access elements in the array, by name it and write only one squared parentheses []
, and inside them, add the row and column, and separate them with the comma ,
.
现在您可以访问数组中的元素,通过名称和只写一个方括号[],在其中添加行和列,并将它们与逗号分开。
The following code below access an element in 2nd row and 1st column of the array I already created in previous code above:
下面的代码访问了前面代码中已经创建的数组的第2行和第1列中的元素:
arr[0, 1]
writing only this line is to read the value in that cell, i.e. get the value in this cell, but if you add the equal =
sign, you are about to write the value in that cell, i.e. set the value in this cell. You also can use the +=, -=, *= and /= operators of course, for numbers only (int, float, double, __int16, __int32, __int64 and etc), but sure you know it already.
只写这一行,就是读取该单元格中的值,即获取该单元格中的值,但如果添加等号,则将写入该单元格中的值,即设置该单元格中的值。您还可以使用+=、-=、*=和/=操作符,仅对数字(int、float、double、__int16、__int32、__int64等),但您肯定已经知道了。
If your project is not CLI, then you can use the unmanaged array class of the std namespace, if you #include <array>
, of course, but the problem is that this array class is different than the CLI array. Create array of this type is same like the CLI, except that you will have to remove the ^
sign and the gcnew
keyword. But unfortunately the second int parameter in the <>
parentheses specifies the length (i.e. size) of the array, not its rank!
如果您的项目不是CLI,那么您可以使用std名称空间的非托管数组类,如果您包括
There is no way to specify rank in this kind of array, rank is CLI array's feature only..
在这种数组中没有指定rank的方法,rank是CLI数组的特性。
std array behaves like normal array in c++, that you define with pointer, for example int*
and then: new int[size]
, or without pointer: int arr[size]
, but unlike the normal array of the c++, std array provides functions that you can use with the elements of the array, like fill, begin, end, size, and etc, but normal array provides nothing.
性病阵列像正常的数组在c++中,您定义的指针,例如int *然后:新int(大小),或没有指针:int arr(大小),但与正常的c++数组,性病数组提供功能,您可以使用数组的元素,像填满,开始,结束,大小等,但正常的阵列提供了什么。
But still std array are one dimensional array, like the normal c++ arrays. But thanks to the solutions that the other guys suggest about how you can make the normal c++ one dimensional array to two dimensional array, we can adapt the same ideas to std array, e.g. according to Mehrdad Afshari's idea, we can write the following code:
但是std数组仍然是一维数组,就像普通的c++数组一样。但是由于其他的解决方案,其他的人建议如何使普通的c++一维数组到二维数组,我们可以将相同的想法应用到std阵列中,例如根据Mehrdad Afshari的想法,我们可以编写如下代码:
array<array<int, 3>, 2> array2d = array<array<int, 3>, 2>();
This line of code creates a "jugged array", which is an one dimensional array that each of its cells is or points to another one dimensional array.
这行代码创建了一个“jugged array”,它是一个一维数组,每个单元格都是或指向另一个一维数组。
If all one dimensional arrays in one dimensional array are equal in their length/size, then you can treat the array2d variable as a real two dimensional array, plus you can use the special methods to treat rows or columns, depends on how you view it in mind, in the 2D array, that std array supports.
如果所有的一维数组,一维数组长度/尺寸是相等的,那么你可以把array2d变量当作一个真正的二维数组,以及您可以使用特殊的方法来治疗行或列,取决于你如何看待它,性病的二维数组,数组的支持。
You also can use Kevin Loney's solution:
你也可以使用Kevin Loney的解决方案:
int *ary = new int[sizeX*sizeY];
// ary[i][j] is then rewritten as
ary[i*sizeY+j]
but if you use std array, the code must look different:
但是如果使用std数组,代码必须看起来不同:
array<int, sizeX*sizeY> ary = array<int, sizeX*sizeY>();
ary.at(i*sizeY+j);
And still have the unique functions of the std array.
还有std阵列的独特功能。
Note that you still can access the elements of the std array using the []
parentheses, and you don't have to call the at
function. You also can define and assign new int variable that will calculate and keep the total number of elements in the std array, and use its value, instead of repeating sizeX*sizeY
注意,您仍然可以使用[]括号访问std数组的元素,并且您不必调用at函数。您还可以定义和分配新的int变量,该变量将计算并保留std数组中元素的总数,并使用其值,而不是重复sizeX*sizeY。
You can define your own two dimensional array generic class, and define the constructor of the two dimensional array class to receive two integers to specify the number of rows and columns in the new two dimensional array, and define get function that receive two parameters of integer that access an element in the two dimensional array and returns its value, and set function that receives three parameters, that the two first are integers that specify the row and column in the two dimensional array, and the third parameter is the new value of the element. Its type depends on the type you chose in the generic class.
您可以定义您自己的二维数组泛型类,并定义二维数组类的构造函数接受两个整数指定的行数和列的二维数组,并定义函数接受两个参数的整数,访问二维数组中的一个元素,并返回它的值,并设置函数接受三个参数,一分之二是整数指定行和列的二维数组,和第三个参数是元素的新值。它的类型取决于您在泛型类中选择的类型。
You will be able to implement all this by using either the normal c++ array (pointers or without) or the std array and use one of the ideas that other people suggested, and make it easy to use like the cli array, or like the two dimensional array that you can define, assign and use in C#.
你将能够实现所有通过正常使用c++数组指针(或没有)或性病数组和使用的一个想法别人建议,并使其易于使用和cli数组一样,或者像二维数组,您可以定义、分配和在c#中使用。
#17
1
I have left you with a solution which works the best for me, in certain cases. Especially if one knows [the size of?] one dimension of the array. Very useful for an array of chars, for instance if we need an array of varying size of arrays of char[20].
在某些情况下,我给了你一个最适合我的解决方案。特别是如果你知道(尺寸)]数组的一维。对于一个字符数组非常有用,例如,如果我们需要一个字符数组大小不等的数组[20]。
int size = 1492;
char (*array)[20];
array = new char[size][20];
...
strcpy(array[5], "hola!");
...
delete [] array;
The key is the parentheses in the array declaration.
关键是数组声明中的圆括号。
#18
1
I used this not elegant but FAST,EASY and WORKING system. I do not see why can not work because the only way for the system to allow create a big size array and access parts is without cutting it in parts:
我用的不是优雅,而是快速,简单和工作的系统。我不明白为什么不能工作,因为系统允许创建一个大尺寸数组和访问部件的唯一方法是不把它分割成部分:
#define DIM 3
#define WORMS 50000 //gusanos
void halla_centros_V000(double CENW[][DIM])
{
CENW[i][j]=...
...
}
int main()
{
double *CENW_MEM=new double[WORMS*DIM];
double (*CENW)[DIM];
CENW=(double (*)[3]) &CENW_MEM[0];
halla_centros_V000(CENW);
delete[] CENW_MEM;
}
#19
-1
declaring 2D array dynamically:
声明动态二维数组:
#include<iostream>
using namespace std;
int main()
{
int x = 3, y = 3;
int **ptr = new int *[x];
for(int i = 0; i<y; i++)
{
ptr[i] = new int[y];
}
srand(time(0));
for(int j = 0; j<x; j++)
{
for(int k = 0; k<y; k++)
{
int a = rand()%10;
ptr[j][k] = a;
cout<<ptr[j][k]<<" ";
}
cout<<endl;
}
}
Now in the above code we took a double pointer and assigned it a dynamic memory and gave a value of the columns. Here the memory allocated is only for the columns, now for the rows we just need a for loop and assign the value for every row a dynamic memory. Now we can use the pointer just the way we use a 2D array. In the above example we then assigned random numbers to our 2D array(pointer).Its all about DMA of 2D array.
在上面的代码中,我们使用了一个双指针并赋予它一个动态内存并给出了列的值。这里分配的内存仅用于列,现在对于行,我们只需要一个for循环,并为每个行分配一个动态内存的值。现在我们可以使用指针,就像我们使用2D数组一样。在上面的示例中,我们将随机数分配给我们的2D数组(指针)。它的全部关于DMA的二维数组。
#20
-1
I'm using this when creating dynamic array. If you have a class or a struct. And this works. Example:
我在创建动态数组时使用这个。如果你有一个类或结构。这工作。例子:
struct Sprite {
int x;
};
int main () {
int num = 50;
Sprite **spritearray;//a pointer to a pointer to an object from the Sprite class
spritearray = new Sprite *[num];
for (int n = 0; n < num; n++) {
spritearray[n] = new Sprite;
spritearray->x = n * 3;
}
//delete from random position
for (int n = 0; n < num; n++) {
if (spritearray[n]->x < 0) {
delete spritearray[n];
spritearray[n] = NULL;
}
}
//delete the array
for (int n = 0; n < num; n++) {
if (spritearray[n] != NULL){
delete spritearray[n];
spritearray[n] = NULL;
}
}
delete []spritearray;
spritearray = NULL;
return 0;
}
#21
-1
This is not the one in much details, but quite simplified.
这不是很多细节中的一个,但是非常简单。
int *arrayPointer = new int[4][5][6]; // ** LEGAL**
int *arrayPointer = new int[m][5][6]; // ** LEGAL** m will be calculated at run time
int *arrayPointer = new int[3][5][]; // ** ILLEGAL **, No index can be empty
int *arrayPointer = new int[][5][6]; // ** ILLEGAL **, No index can be empty
Remember:
记住:
1. ONLY THE THE FIRST INDEX CAN BE A RUNTIME VARIABLE. OTHER INDEXES NEED TO BE CONSTANT
1。只有第一个索引可以是一个运行时变量。其他指标需要保持不变。
2. NO INDEX CAN BE LEFT EMPTY.
2。索引不能空。
As mentioned in other answers, call
如其他答案所述,请打电话。
delete arrayPointer;
to deallocate memory associated with the array when you are done with the array.
当您完成数组时,将与数组关联的内存分配。