如何在C ++中创建动态数组数组 [英] How to create Array of Dynamic Arrays in C++
问题描述
我试图学习C ++并尝试为一个简单的哈希表写一个代码,如下面的结构:
I am trying to learn C++ and trying to write a code for a simple hash table like following structure:
array[0][0] array[0][1] array[0][2]
key 1 value 1 value 2
array[1][0] array[1][1]
key 2 value 3
array[2][0] array[2][1] array[2][2]
key 3 value 4 value 5
表示动态数组数组。现在,我不明白如何定义数组这样?
means Array of Dynamic Arrays. Now, I can't understand how to define the array like that ?
任何帮助将是感激。
推荐答案
如果真的需要创建一个动态数组动态数组,你必须使用 new
两个数组的关键字。例如:
If you really did need to create a dynamic array of dynamic arrays you would have to do it using the new
keyword for both arrays. For example:
// an array of int pointers... each points to the start of an array
int** arrays = new int*[10];
arrays[0] = new int[99]; // populate the first element of the array of arrays
arrays[1] = new int[47]; // arrays don't have to be the same size.
当然,我强烈建议不要这样做。您必须记住在数组
和数组的每个成员上使用
本身。 delete []
Of course I highly recommend NOT doing this. You have to then remember to use delete[]
on each member of arrays
and on arrays
itself.
真的你应该使用内置的 std :: vector
这个。这是为什么它在那里(我投票的其他答案!)
Really you should use the built in std::vector
type for this. It is why it is there (I voted for the other answers!).
只是作为一个注释,这不是连续的内存。如果你希望成员数组的大小相同,你可以在中为
循环分配它们的内存。
Just as a note, this is not contiguous memory either. Also if you do want the member arrays to be the same size you could allocate their memory in a for
loop.
这篇关于如何在C ++中创建动态数组数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!