"Free" C++ 中的数组元素

"Free" array element in c++

本文关键字:数组元素 C++ Free      更新时间:2023-10-16

我有一个对象数组

Timed_packet* send_queue = new Timed_packet[num_sequence_numbers]; // size=10

它将在某一时刻被Timed_ packets填充,有没有删除或释放其中的元素,然后将数组向左移动以替换已释放的元素?

示例

send_queue = [ packet 9, packet 8, packet 7, packet 6, packet 5, packet 4, packet 3, packet 2, packet 1, packet 0]   

我想删除数据包5和它左边的所有内容,使send_queue看起来像

send_queue = [ packet 4, packet 3, packet 2, packet 1, empty, empty, empty, empty, empty, empty]

有什么方法可以实现这一点吗?

您不能通过删除或释放元素来实现这一点,因为您已经将数组分配为单个内存区域。该地区只能从整体上解放,而不能局部解放。

不过,正如其他人所提到的,您可以使用各种技术来"虚拟化"阵列,使其看起来像是元素来来往往:

packet *queue = new packet[queue_capacity];
packet *begin = queue, *end = queue+queue_capacity, *first = queue, *last = queue;
// add an element to the queue
packet p(...);
*last++ = *p; // note postincrement
if (last == end) last = begin; // the queue is cyclic
if (last == first) throw new queue_overflow(); // ran out of room in the queue!
// remove an element from the queue
if (first==last) throw new queue_underflow(); // ran out of items in the queue!
packet p = *first++; // taken by copy; note postincrement
if (first == end) first = begin; // the queue is still cyclic

这个代码让我头脑发热。你可能需要修正几个边界条件,但理论是存在的。

如果你使用std::deque,这基本上就是你会得到的,除了后者提供:

  • 性能
  • 便携性
  • 型式安全
  • 边界安全
  • 符合标准

编辑:要改进这一点,可以做的一件事是分配一个指针数组(packet*),而不是一个值数组(packet)。然后,入队/出队操作是指向数据包的指针的副本,而不是数据包的副本。你需要确保数据包是由出队者而不是入队者释放的,但这应该快几光年(原文如此)。

好吧,实现这一点的一种方法是从字面上实现它:通过将"数据包4"复制到数组的开头,将"数据包包3"复制到下一个元素来移动数组中的数据,依此类推。在您的情况下,用代表"空"的任何元素值填充数组中未使用的其余部分。

请记住,C++没有内置的数组"空"元素概念。您将不得不通过创建代表"空"数据包的Timed_packet对象的一些保留状态来手动实现它。或者,您也可以简单地记住,您的数组现在只包含4个元素,而不管状态如何,其余元素都假定为"空"。

是的,您可以手动编写一个循环,将所有内容向左移动,并用"空"值填充其余元素(如果您不使用C++11,可能是nullptrNULL)。