我有一个对象数组
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)。然后,您的入队/出队操作是指向数据包的指针的拷贝,而不是数据包的拷贝。您需要确保数据包被出队者释放,而不是被入队者释放,但这应该快光年(原文如此)。
关于c++ - C++中的"Free"数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12810928/