简体   繁体   English

如何在C ++中增加和缩小双指针动态数组?

[英]How do I grow and shrink a double-pointer dynamic array in C++?

I'm learning C++ and I'm expected to use a double pointer to build a dynamic array of objects that grows and shrinks as elements are added and removes from the array. 我正在学习C ++,并且期望使用双指针来构建动态对象数组,该对象数组会随着元素的添加和删除而增加和缩小。

I can create the array like so: 我可以这样创建数组:

Person** people = new Person*[10];

And add objects like so: 并添加如下对象:

people[0] = new Person(“Luke”);
people[1] = new Person(“Han”);
people[2] = new Person(“Leia”);

And delete objects like so: 并删除对象,如下所示:

delete people[1]
people[1] = null;

(At least I think that's correct.) (至少我认为是正确的。)

But I'm stuck on several things... 但是我在几件事上陷入困境...

Questions: 问题:

Once the array is full with 10 items, how do I dynamically add more space for additional objects? 一旦数组中充满了10个项目,如何动态地为其他对象添加更多空间? In fact, I'm thinking the array should probably have a size of 0 before the first item is added; 实际上,我认为在添加第一项之前,数组的大小可能应该为0; how do I do that? 我怎么做?

Similarly, when I delete an item (like when I delete people[1], above), how do I shrink the array down to a minimum size? 同样,当我删除一个项目时(如上面的删除people [1]一样),如何将数组缩小到最小大小? Like, how do I make the object at people[2] move to the position of people[1]? 例如,如何使对象在人[2]上移动到人[1]的位置?

Any suggestions or help is greatly appreciated, thanks! 任何建议或帮助,不胜感激,谢谢!

rh RH

您需要创建一个更大的新数组,并从当前数组中复制数据并取消分配。

You need to implement reallocation . 您需要实现重新分配

Basically you create a second, bigger (or smaller) array, copy the existing elements there, and then discard the old array. 基本上,您创建了另一个更大或更小的数组,将现有元素复制到那里,然后丢弃旧数组。

Do note, that you just need to copy the pointers. 请注意,您只需要复制指针。 The objects themselves do not need to change. 对象本身不需要更改。

Under the hood, std::vector does the same thing. 在幕后, std::vector做同样的事情。

A common practice, when creating a bigger array, is to multiply its size by a factor somewhere between 1.5-2. 创建更大的数组时,通常的做法是将其大小乘以1.5-2之间的某个倍数。


When removing an element, you need to shift all elements at higher indeces one element lower. 删除元素时,需要将所有元素移至较高位置,将元素移至较低位置。 Again, you just need to move the pointers, not the objects themselves. 同样,您只需要移动指针,而不是对象本身。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM