作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我正在尝试学习 C++ 并尝试为如下结构的简单哈希表编写代码:
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
表示动态数组的数组。现在,我不明白如何定义这样的数组?
如有任何帮助,我们将不胜感激。
最佳答案
如果您真的确实需要创建动态数组的动态数组,则必须对这两个数组都使用new
关键字。例如:
// 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.
当然,我强烈建议不要这样做。然后,您必须记住对 arrays
的每个成员和 arrays
本身使用 delete[]
。
实际上,您应该为此使用内置的 std::vector
类型。这就是它在那里的原因(我投票支持其他答案!)。
请注意,这也不是连续内存。此外,如果您确实希望成员数组的大小相同,您可以在 for
循环中分配它们的内存。
关于c++ - 如何在 C++ 中创建动态数组数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13192093/
我是一名优秀的程序员,十分优秀!