我不明白如何在C ++中创建和使用动态数组

时间:2023-01-25 20:05:59

Okay so I have;

好的,我有;

int grid_x = 5
int * grid;
grid = new int[grid_x];
*grid = 34;
cout << grid[0];

Should line 3 create an array with 5 elements? Or fill the first element with the number 5?

第3行应该创建一个包含5个元素的数组吗?或者用数字5填充第一个元素?

Line 4 fills the first element, how do I fill the rest?

第4行填充第一个元素,如何填充其余元素?

Without line 4, line 5 reads "-842150451".

没有第4行,第5行读取“-842150451”。

I don't understand what is going on, I'm trying to create a 2 dimensional array using x and y values specified by the user, and then fill each element one by one with numeric values also specified by the user. My above code was an attempt to try it out with a 1 dimensional array first.

我不明白发生了什么,我正在尝试使用用户指定的x和y值创建一个二维数组,然后逐个用用户指定的数值填充每个元素。我上面的代码是尝试首先使用1维数组进行尝试。

6 个解决方案

#1


9  

Should line 3 create an array with 5 elements?

第3行应该创建一个包含5个元素的数组吗?

Yes. It won't initialise them though, which is why you see a weird value.

是。它不会初始化它们,这就是为什么你会看到一个奇怪的值。

Or fill the first element with the number 5?

或者用数字5填充第一个元素?

new int(grid_x), with round brackets, would create a single object, not an array, and specify the initial value.

带有圆括号的new int(grid_x)将创建单个对象,而不是数组,并指定初始值。

There's no way to allocate an array with new and initialise them with a (non-zero) value. You'll have to assign the values after allocation.

无法使用new分配数组并使用(非零)值初始化它们。您必须在分配后分配值。

Line 4 fills the first element, how do I fill the rest?

第4行填充第一个元素,如何填充其余元素?

You can use the subscript operator [] to access elements:

您可以使用下标运算符[]来访问元素:

grid[0] = 34;  // Equivalent to: *(grid)   = 34
grid[1] = 42;  // Equivalent to: *(grid+1) = 42
// ...
grid[4] = 77;  // That's the last one: 5 elements from 0 to 4.

However, you usually don't want to juggle raw pointers like this; the burden of having to delete[] the array when you've finished with it can be difficult to fulfill. Instead, use the standard library. Here's one way to make a two-dimensional grid:

但是,你通常不想像这样处理原始指针;当你完成它时必须删除[]数组的负担可能很难实现。而是使用标准库。这是制作二维网格的一种方法:

#include <vector>

std::vector<std::vector<int>> grid(grid_x, std::vector<int>(grid_y));
grid[x][y] = 42; // for any x is between 0 and grid_x-1, y between 0 and grid_y-1

Or might be more efficient to use a single contiguous array; you'll need your own little functions to access that as a two-dimenionsal grid. Something like this might be a good starting point:

或者使用单个连续数组可能更有效;你需要自己的小函数来访问它作为一个二维网格。这样的事情可能是一个很好的起点:

template <typename T>
class Grid {
public:
    Grid(size_t x, size_t y) : size_x(x), size_y(y), v(x*y) {}

    T       & operator()(size_t x, size_t y)       {return v[y*size_x + x];}
    T const & operator()(size_t x, size_t y) const {return v[y*size_x + x];}

private:
    size_t size_x, size_y;
    std::vector<T> v;
};

Grid grid(grid_x,grid_y);
grid(x,y) = 42;

#2


11  

The default C++ way of creating a dynamic(ally resizable) array of int is:

创建动态(可调整大小)int数组的默认C ++方法是:

std::vector<int> grid;

Don't play around with unsafe pointers and manual dynamic allocation when the standard library already encapsulates this for you.

当标准库已经为您封装时,不要使用不安全的指针和手动动态分配。

To create a vector of 5 elements, do this:

要创建5个元素的向量,请执行以下操作:

std::vector<int> grid(5);

You can then access its individual elements using []:

然后,您可以使用[]访问其各个元素:

grid[0] = 34;
grid[1] = 42;

You can add new elements to the back:

您可以在后面添加新元素:

// grid.size() is 5
grid.push_back(-42);
// grid.size() now returns 6

Consult reference docs to see all operations available on std::vector.

请参阅参考文档以查看std :: vector上可用的所有操作。

#3


1  

Should line 3 create an array with 5 elements? Or fill the first element with the number 5?

第3行应该创建一个包含5个元素的数组吗?或者用数字5填充第一个元素?

Create an array with 5 elements.

创建一个包含5个元素的数组。

Line 4 fills the first element, how do I fill the rest?

第4行填充第一个元素,如何填充其余元素?

grid[n] = x;

Where n is the index of the element you want to set and x is the value.

其中n是要设置的元素的索引,x是值。

#4


0  

Line 3 allocates memory for 5 integers side by side in memory so that they can be accessed and modified by...

第3行在内存中并排分配5个整数的内存,以便可以通过...访问和修改它们。

The bracket operator, x[y] is exactly equivalent to *(x+y), so you could change Line 4 to grid[0] = 34; to make it more readable (this is why grid[2] will do the same thing as 2[grid]!)

括号运算符x [y]与*(x + y)完全等价,因此您可以将第4行更改为grid [0] = 34;使它更具可读性(这就是为什么grid [2]会做与2 [grid]相同的事情!)

#5


0  

An array is simply a contiguous block of memory. Therefore it has a starting address.

数组只是一个连续的内存块。因此它有一个起始地址。

int * grid;

Is the C representation of the address of an integer, you can read the * as 'pointer'. Since your array is an array of integers, the address of the first element in the array is effectively the same as the address of the array. Hence line 3

是整数地址的C表示,您可以将*读作'指针'。由于您的数组是整数数组,因此数组中第一个元素的地址实际上与数组的地址相同。因此第3行

grid = new int[grid_x];

grid = new int [grid_x];

allocates enough memory (on the heap) to hold the array and places its address in the grid variable. At this point the content of that memory is whatever it was when the physical silicon was last used. Reading from uninitialised memory will result in unpredictable values, hence your observation that leaving out line 4 results in strange output.

分配足够的内存(在堆上)来保存数组并将其地址放在网格变量中。此时,该内存的内容与上次使用物理芯片时的内容无关。从未初始化的内存中读取将导致不可预测的值,因此您观察到遗漏第4行会导致奇怪的输出。

Remember that * pointer? On line four you can read it as 'the content of the pointer' and therefore

还记得*指针吗?在第四行,您可以将其读作“指针的内容”,因此

*grid = 34;

means set the content of the memory pointed to by grid to the value 34. But line 3 gave grid the address of the first element of the array. So line 4 sets the first element of the array to be 34.

意味着将网格指向的内存的内容设置为值34.但是第3行给出了网格数组的第一个元素的地址。因此第4行将数组的第一个元素设置为34。

In C, arrays use a zero-based index, which means that the first element of the array is number 0 and the last is number-of-elements-in-the-array - 1. So one way of filling the array is to index each element in turn to set a value to it.

在C中,数组使用从零开始的索引,这意味着数组的第一个元素是数字0,最后一个是数组中的元素数 - 1.所以填充数组的一种方法是依次索引每个元素以为其设置值。

for(int index = 0; index < grid_x; index++)
{
    grid[index] = 34;
}

Alternatively, you could continue to use a pointer to do the same job.

或者,您可以继续使用指针执行相同的工作。

for(int* pointerToElement = grid; 0 < grid_x; grid_x-- )
{
    // save 34 to the address held by the pointer
    /// and post-increment the pointer to the next element.
    *pointerToElement++ = 34;
}

Have fun with arrays and pointers, they consistently provide a huge range of opportunities to spend sleepless hours wondering why your code doesn't work, PC reboots, router catches fire, etc, etc.

享受数组和指针带来的乐趣,他们不断提供大量的机会来度过无眠时间,想知道为什么你的代码不起作用,PC重启,路由器着火等等。

#6


0  

int grid_x = 5 
int * grid; 
grid = new int[grid_x];
*grid = 34; 
cout << grid[0];

Should line 3 create an array with 5 elements? Or fill the first
element with the number 5?

Definitely the former. With the operator "new" you are allocating memory

绝对是前者。使用运算符“new”,您将分配内存

Line 4 fills the first element, how do I fill the rest?

第4行填充第一个元素,如何填充其余元素?

Use operator [], e.g.:

使用operator [],例如:

for int (i=0; i < grid_x; i++) { //Reset the buffer
  grid[i] = 0;
}


Without line 4, line 5 reads "-842150451".

没有第4行,第5行读取“-842150451”。

You are just reading uninitialized memory, it could be any value.

你只是阅读未初始化的内存,它可以是任何值。

I don't understand what is going on, I'm trying to create a 2 dimensional array using x and y values specified by the user, and then fill each element one by one with numeric values also specified by the user. My above code was an attempt to try it out with a 1 dimensional array first.

我不明白发生了什么,我正在尝试使用用户指定的x和y值创建一个二维数组,然后逐个用用户指定的数值填充每个元素。我上面的代码是尝试首先使用1维数组进行尝试。

Other users explained how to use vectors. If you have to set only once the size of your array, I usually prefer boost::scoped_array which takes care of deleting when the variable goes out of scope.

其他用户解释了如何使用向量。如果你只需要设置一次数组的大小,我通常更喜欢boost :: scoped_array,它在变量超出范围时负责删除。

For a two dimensional array of size not known at compile time, you need something a little bit trickier, like a scoped_array of scoped_arrays. Creating it will require necessarily a for loop, though.

对于编译时未知的二维数组,您需要一些有点棘手的东西,比如scoped_arrays的scoped_array。但是,创建它将需要一个for循环。

using boost::scoped_array;
int grid_x;
int grid_y;
///Reading values from user...
scoped_array<scoped_array<int> > grid(new scoped_array<int> [grid_x]);
for (int i = 0; i < grid_x; i++)
  grid[i] = scoped_array<int>(new int[grid_y] );

You will be able then to access your grid elements as

然后,您就可以访问网格元素了

grid[x][y];

Note: It would work also taking scoped_array out of the game,

注意:它也可以将scoped_array从游戏中移除,

typedef int* p_int_t;
p_int_t* grid = new p_int_t [grid_x];
for (int i = 0; i < grid_x; i++)
  grid[i] = new int[grid_y];

but then you would have to take care of deletion at the end of the array's life, of ALL sub arrays.

但是你必须在数组的生命周期结束时对所有子数组进行删除。

#1


9  

Should line 3 create an array with 5 elements?

第3行应该创建一个包含5个元素的数组吗?

Yes. It won't initialise them though, which is why you see a weird value.

是。它不会初始化它们,这就是为什么你会看到一个奇怪的值。

Or fill the first element with the number 5?

或者用数字5填充第一个元素?

new int(grid_x), with round brackets, would create a single object, not an array, and specify the initial value.

带有圆括号的new int(grid_x)将创建单个对象,而不是数组,并指定初始值。

There's no way to allocate an array with new and initialise them with a (non-zero) value. You'll have to assign the values after allocation.

无法使用new分配数组并使用(非零)值初始化它们。您必须在分配后分配值。

Line 4 fills the first element, how do I fill the rest?

第4行填充第一个元素,如何填充其余元素?

You can use the subscript operator [] to access elements:

您可以使用下标运算符[]来访问元素:

grid[0] = 34;  // Equivalent to: *(grid)   = 34
grid[1] = 42;  // Equivalent to: *(grid+1) = 42
// ...
grid[4] = 77;  // That's the last one: 5 elements from 0 to 4.

However, you usually don't want to juggle raw pointers like this; the burden of having to delete[] the array when you've finished with it can be difficult to fulfill. Instead, use the standard library. Here's one way to make a two-dimensional grid:

但是,你通常不想像这样处理原始指针;当你完成它时必须删除[]数组的负担可能很难实现。而是使用标准库。这是制作二维网格的一种方法:

#include <vector>

std::vector<std::vector<int>> grid(grid_x, std::vector<int>(grid_y));
grid[x][y] = 42; // for any x is between 0 and grid_x-1, y between 0 and grid_y-1

Or might be more efficient to use a single contiguous array; you'll need your own little functions to access that as a two-dimenionsal grid. Something like this might be a good starting point:

或者使用单个连续数组可能更有效;你需要自己的小函数来访问它作为一个二维网格。这样的事情可能是一个很好的起点:

template <typename T>
class Grid {
public:
    Grid(size_t x, size_t y) : size_x(x), size_y(y), v(x*y) {}

    T       & operator()(size_t x, size_t y)       {return v[y*size_x + x];}
    T const & operator()(size_t x, size_t y) const {return v[y*size_x + x];}

private:
    size_t size_x, size_y;
    std::vector<T> v;
};

Grid grid(grid_x,grid_y);
grid(x,y) = 42;

#2


11  

The default C++ way of creating a dynamic(ally resizable) array of int is:

创建动态(可调整大小)int数组的默认C ++方法是:

std::vector<int> grid;

Don't play around with unsafe pointers and manual dynamic allocation when the standard library already encapsulates this for you.

当标准库已经为您封装时,不要使用不安全的指针和手动动态分配。

To create a vector of 5 elements, do this:

要创建5个元素的向量,请执行以下操作:

std::vector<int> grid(5);

You can then access its individual elements using []:

然后,您可以使用[]访问其各个元素:

grid[0] = 34;
grid[1] = 42;

You can add new elements to the back:

您可以在后面添加新元素:

// grid.size() is 5
grid.push_back(-42);
// grid.size() now returns 6

Consult reference docs to see all operations available on std::vector.

请参阅参考文档以查看std :: vector上可用的所有操作。

#3


1  

Should line 3 create an array with 5 elements? Or fill the first element with the number 5?

第3行应该创建一个包含5个元素的数组吗?或者用数字5填充第一个元素?

Create an array with 5 elements.

创建一个包含5个元素的数组。

Line 4 fills the first element, how do I fill the rest?

第4行填充第一个元素,如何填充其余元素?

grid[n] = x;

Where n is the index of the element you want to set and x is the value.

其中n是要设置的元素的索引,x是值。

#4


0  

Line 3 allocates memory for 5 integers side by side in memory so that they can be accessed and modified by...

第3行在内存中并排分配5个整数的内存,以便可以通过...访问和修改它们。

The bracket operator, x[y] is exactly equivalent to *(x+y), so you could change Line 4 to grid[0] = 34; to make it more readable (this is why grid[2] will do the same thing as 2[grid]!)

括号运算符x [y]与*(x + y)完全等价,因此您可以将第4行更改为grid [0] = 34;使它更具可读性(这就是为什么grid [2]会做与2 [grid]相同的事情!)

#5


0  

An array is simply a contiguous block of memory. Therefore it has a starting address.

数组只是一个连续的内存块。因此它有一个起始地址。

int * grid;

Is the C representation of the address of an integer, you can read the * as 'pointer'. Since your array is an array of integers, the address of the first element in the array is effectively the same as the address of the array. Hence line 3

是整数地址的C表示,您可以将*读作'指针'。由于您的数组是整数数组,因此数组中第一个元素的地址实际上与数组的地址相同。因此第3行

grid = new int[grid_x];

grid = new int [grid_x];

allocates enough memory (on the heap) to hold the array and places its address in the grid variable. At this point the content of that memory is whatever it was when the physical silicon was last used. Reading from uninitialised memory will result in unpredictable values, hence your observation that leaving out line 4 results in strange output.

分配足够的内存(在堆上)来保存数组并将其地址放在网格变量中。此时,该内存的内容与上次使用物理芯片时的内容无关。从未初始化的内存中读取将导致不可预测的值,因此您观察到遗漏第4行会导致奇怪的输出。

Remember that * pointer? On line four you can read it as 'the content of the pointer' and therefore

还记得*指针吗?在第四行,您可以将其读作“指针的内容”,因此

*grid = 34;

means set the content of the memory pointed to by grid to the value 34. But line 3 gave grid the address of the first element of the array. So line 4 sets the first element of the array to be 34.

意味着将网格指向的内存的内容设置为值34.但是第3行给出了网格数组的第一个元素的地址。因此第4行将数组的第一个元素设置为34。

In C, arrays use a zero-based index, which means that the first element of the array is number 0 and the last is number-of-elements-in-the-array - 1. So one way of filling the array is to index each element in turn to set a value to it.

在C中,数组使用从零开始的索引,这意味着数组的第一个元素是数字0,最后一个是数组中的元素数 - 1.所以填充数组的一种方法是依次索引每个元素以为其设置值。

for(int index = 0; index < grid_x; index++)
{
    grid[index] = 34;
}

Alternatively, you could continue to use a pointer to do the same job.

或者,您可以继续使用指针执行相同的工作。

for(int* pointerToElement = grid; 0 < grid_x; grid_x-- )
{
    // save 34 to the address held by the pointer
    /// and post-increment the pointer to the next element.
    *pointerToElement++ = 34;
}

Have fun with arrays and pointers, they consistently provide a huge range of opportunities to spend sleepless hours wondering why your code doesn't work, PC reboots, router catches fire, etc, etc.

享受数组和指针带来的乐趣,他们不断提供大量的机会来度过无眠时间,想知道为什么你的代码不起作用,PC重启,路由器着火等等。

#6


0  

int grid_x = 5 
int * grid; 
grid = new int[grid_x];
*grid = 34; 
cout << grid[0];

Should line 3 create an array with 5 elements? Or fill the first
element with the number 5?

Definitely the former. With the operator "new" you are allocating memory

绝对是前者。使用运算符“new”,您将分配内存

Line 4 fills the first element, how do I fill the rest?

第4行填充第一个元素,如何填充其余元素?

Use operator [], e.g.:

使用operator [],例如:

for int (i=0; i < grid_x; i++) { //Reset the buffer
  grid[i] = 0;
}


Without line 4, line 5 reads "-842150451".

没有第4行,第5行读取“-842150451”。

You are just reading uninitialized memory, it could be any value.

你只是阅读未初始化的内存,它可以是任何值。

I don't understand what is going on, I'm trying to create a 2 dimensional array using x and y values specified by the user, and then fill each element one by one with numeric values also specified by the user. My above code was an attempt to try it out with a 1 dimensional array first.

我不明白发生了什么,我正在尝试使用用户指定的x和y值创建一个二维数组,然后逐个用用户指定的数值填充每个元素。我上面的代码是尝试首先使用1维数组进行尝试。

Other users explained how to use vectors. If you have to set only once the size of your array, I usually prefer boost::scoped_array which takes care of deleting when the variable goes out of scope.

其他用户解释了如何使用向量。如果你只需要设置一次数组的大小,我通常更喜欢boost :: scoped_array,它在变量超出范围时负责删除。

For a two dimensional array of size not known at compile time, you need something a little bit trickier, like a scoped_array of scoped_arrays. Creating it will require necessarily a for loop, though.

对于编译时未知的二维数组,您需要一些有点棘手的东西,比如scoped_arrays的scoped_array。但是,创建它将需要一个for循环。

using boost::scoped_array;
int grid_x;
int grid_y;
///Reading values from user...
scoped_array<scoped_array<int> > grid(new scoped_array<int> [grid_x]);
for (int i = 0; i < grid_x; i++)
  grid[i] = scoped_array<int>(new int[grid_y] );

You will be able then to access your grid elements as

然后,您就可以访问网格元素了

grid[x][y];

Note: It would work also taking scoped_array out of the game,

注意:它也可以将scoped_array从游戏中移除,

typedef int* p_int_t;
p_int_t* grid = new p_int_t [grid_x];
for (int i = 0; i < grid_x; i++)
  grid[i] = new int[grid_y];

but then you would have to take care of deletion at the end of the array's life, of ALL sub arrays.

但是你必须在数组的生命周期结束时对所有子数组进行删除。