gpt4 book ai didi

c++ - 如何在 C++ 中创建动态数组数组

转载 作者:太空狗 更新时间:2023-10-29 23:33:31 25 4
gpt4 key购买 nike

我正在尝试学习 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com