"Free" C++ 中的数组元素
"Free" array element in c++
我有一个对象数组
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,可能是nullptr
或NULL
)。
- 数组元素打印的递归方法
- 如何将字节数组元素替换为修改的十六进制 ASCII 符号?
- 为什么使用数组元素查找最大数字的程序不起作用?
- 数组元素更改值?
- 如何访问宏中定义的数组元素
- 将数组元素递增 1
- C++函数,它将数组、谓词和运算符作为参数,并将运算符应用于满足谓词的数组元素
- 存储指向动态数组元素的指针
- C++通过别名指针以静默方式将错误的类型分配给数组元素
- 在 std::map 中插入数组元素
- 使用指针访问数组元素时出现意外结果
- c++ 使用动态分配运算符反向数组元素
- 为什么在 c++ 中分配 char 数组元素时,分配的字符会被销毁?
- 缺少数组元素问题
- 如何在类中制作 2D 数组元素,然后在其构造函数中指定其维度?
- 创建一个函数来转换数组元素的类型并返回数组的地址
- 删除在结构 c++ 中声明的数组元素
- Getter 和 Setter 用于类 C++ 中的数组元素
- 尝试递归获取数组元素的总和
- 使用SWIG将numpy数组元素(int)传递给c++int