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

时间:2019-09-18 02:53:43

标签: c++ arraylist

我正在将元素列表读入数组,然后插入一个元素,然后删除一个元素。我已经获得插入代码的代码了。我也得到了它删除我想要的元素,但是在删除后它只会输出一个元素。

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。被删除元素之后的下一个元素确实会上移,但是此后的其余元素不会输出。我没有编译器错误。

1 个答案:

答案 0 :(得分:0)

这有一个错误:

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;
    }
}
相关问题