初学者从结构数组中删除第一个元素(C) [英] Beginner Removing first element from an array of structs (C)

查看:514
本文介绍了初学者从结构数组中删除第一个元素(C)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个结构数组(实际上是一个按优先级排序的堆数组).

I have an array of structs (actually it's a heap array sorted by priority).

 typedef struct {
    char name[MAX_CHARACTERS+1];
    int priority;
} person;
person p[MAX_HEAPSIZE+1];

,并想要删除数组中的第一个元素.我不确定如何或使用什么命令.

and want to remove the first element in the array. I'm not sure how or what command to use.

到目前为止,我一直在做

So far, I've been doing

void remove(){
    swap(0, heapsize-1);
    strcpy(p[heapsize-1].name, p[MAX_HEAP_SIZE+1].name);
    p[heapsize-1].priority = p[MAX_HEAP_SIZE+1].priority;
}

这将交换数组中的第一个和最后一个非空元素.然后,它尝试将空元素处的数据复制到数组中的最后一个非空元素(我要删除的元素).

this swaps the first and last non-empty element in the array. Then it tries to copy the data at an empty element to the last non-empty element (element i want to remove) in the array.

但是我认为它只会复制内存位置.有什么我可以做的简单

but I think it only copies the memory positions. Is there something simple where I can do

p [0] = NULL?

p[0] = NULL?

推荐答案

数组是连续的内存块.因此,如果要删除第一个元素,则必须将以下所有元素移到一个元素的开头:

An array is a continuous block of memory. So if you want to remove the first element, you have to move all the following elements towards the beginning by one element:

void remove(void)
{
    memmove(&p[0], &p[1], (MAX_HEAPSIZE - 1) * sizeof(person));
}

这是非常低效的.弹出第一个元素是一个带有堆的常见操作,因此您通常会采用另一种方法-删除数组的最后一个元素-这非常快,因为该数组的其他元素不受影响./p>

This is pretty inefficient. Popping the first element is a common operation with a heap, so you'd usually do it the other way around - remove the last element of an array - which is very fast, because the other elements of the array aren't affected.

void remove(void)
{
    heapsize--;
}

然后

heapsize可以用作堆顶部元素的索引(当然,假设您保留了heap属性).

heapsize can then be used as the index of the top element of the heap (assuming you preserve the heap property, of course).

如果要用最后一个覆盖数组的第一个元素,并且将不再使用的最后一个元素的内存清零,则可以使用memcpy和memset:

If you want to overwrite the first element of the array with the last one and zero out the memory of the last element, which is not used anymore, you can use memcpy and memset:

void remove(void)
{
    memcpy(&p[0], &p[heapsize - 1], sizeof(person));
    memset(&p[heapsize - 1], 0x00, sizeof(person));
}

严格来说,归零最后一个元素的内存并不是必需的,因为您不应该首先访问它.除了使用memcpy覆盖第一个元素之外,还可以使用strcpy并分配优先级(例如在您的remove中)完成此操作;使用memcpy更加简单.

Zeroing out the memory of the last element is not strictly necessary, though, because you shouldn't be accessing it in the first place. Instead of overwriting the first element with the last using memcpy, it can also be done with strcpy and assignment of the priority (like in your remove); using memcpy is simply easier.

这篇关于初学者从结构数组中删除第一个元素(C)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆