如何删除数组列表中的元素

How do you remove an element in an array list

本文关键字:列表 元素 数组 何删除 删除      更新时间:2023-10-16

我正在将元素列表读取到数组中,然后插入一个元素,然后删除一个元素。我已经让我的代码可以很好地插入一个元素。我也让它删除了我想要的元素,但它在删除后只会输出一个元素。

void deletelist(listtype list[], int& numlist, int id, ofstream& outf)
{
int i, where;
where = 0;
while (where < numlist && id > list[where].id) where++;
if (list[where].id == id)
{
while (where < numlist - 1)
{
list[where] = list[where + 1];
list[numlist] = list[numlist - 1];
numlist--;
}
}
else
{
outf << "The item doesn't appear to be in the list" << endl;
}
}

我希望删除元素之后的元素在列表中向上移动 1。删除元素之后的下一个元素确实向上移动,但之后的其余元素不会输出。我没有编译器错误。

这有一个错误:

while (where < numlist && id > list[where].id) where++;
if (list[where].id == id)
{
…

如果在 while 循环结束时where == numlist(因为找不到id指定的元素(,则list[where]是数组中的无效位置,检查list[where].id是不安全的。

更好:

while (where < numlist && id > list[where].id)
where++;
if ((where < numlist) && (list[where].id == id))
{

但这可能不是你唯一的错误。

您没有说明数组是否经过了最终排序。 您也没有指出numlist是否应该在函数返回之后。

我的看法是假设列表没有排序。 该numlist应反映列表的新大小。 在删除的情况下,这将是numlist = numlist - 1. 这是一个更简单的方法:

void deletelist(listtype list[], int& numlist, int id, ofstream& outf)
{
int where = -1;
// find the element
for (int i = 0; i < numlist; i++)
{
if (id == list[i].id)
{
where = i;
break;
}
else if (list[i].id > id)
{
break;
}
}
if (where != -1)
{
// shift all the elements after "where" over by 1 position to the left
for (int j = where+1; j < numlist; j++)
{
list[j-1] = list[j];
}
// numlist reflects the new size of the list
numlist -= 1;
}
else
{
outf << "The item doesn't appear to be in the list" << endl;
}
}