在C++中从列表中删除项目

3

我有一个程序,想要在列表中插入和删除项目。我的删除函数出了问题。我希望用户告诉我他们想要在列表中删除哪个索引,然后减小列表的大小并将项目移动在一起。

例如:333 222 111 如果我删除第二个数字,则列表将变为 333 111 并且列表的大小会减小到2。

先感谢您!

/*  insert
 *  parameters:
 *    index  -- the place in the list to insert newItem
 *    newItem -- the item to insert into the list
 *  returns:
 *    true -- if the item is successfully inserted
 *    false -- otherwise
 *  precondition:  0 < index
 *  postcondition:  newItem is in postiion "index" of the list
 *  Algorithm:  stuff
 */

bool myList::insert(int index, ListItemType newItem) {
    if (!(index > 0)) {
        cerr << "insert:  precondition failed with index = " << index << endl;
        return false;
    }

    if (size == MAX_LIST) {
        cout << "List is full" << endl;
        return false;
    }

    if (index > size) {
        items[size] = newItem;
        size++;
        return true;
    }

    //list is not full and index is b/w items 1 and size-1
    for (int i = size; i >= index; i--) {
        items[i] = items[i - 1];

    }

    items[index - 1] = newItem;
    size++;

    return true;
}

bool myList::remove(int index) {
    //I tried this but it doesn't work well enough
    if (!(index > 0)) {
        cerr << "insert:  precondition failed with index = " << index << endl;
        return false;
    }

    for (int i = size; i >= 0; i--) {
        items[index] = items[index + 1];

    }

    size--;
    return true;
}

2
除非这是一个学习练习,否则请优先使用 std::list<> - Robᵩ
6
不,std::vector<> - Benjamin Lindley
1
问题在于你的 for 循环。对于目标删除索引后的每个项目,你需要将其向后移动一个位置。你拥有所有信息,但循环逻辑是不正确的。 - Chad
1
是的,就像@BenjaminLindley所说的那样。 - Robᵩ
1
@BenjaminLindley:不是的。如果他在索引中使用了无符号类型,负数将会添加到末尾,因为代码中明确处理了太大的数字,而负数只是一个太大的数字。 - Jan Hudec
显示剩余5条评论
1个回答

2

像其他人说的一样,你应该尝试使用STL。但是根据你目前所拥有的代码,你应该把你的for循环改成像这样:

for (int i = index; i < size - 1; i++)
{
    items[i] = items[i+1];

}

这段代码的作用是,从被删除的项开始,用其后面的项替换每一项。就像向左移动一样。
这不会破坏任何元素,但我猜我们可以放心使用。

它运作正常,你说的“销毁任何元素”是什么意思?@Nick,谢谢! - user1789663
这意味着在删除它们之前,您会失去对它们的控制。但这取决于您如何创建它们。如果newItem不是指针,那就不用担心,它们会自动被删除。 - imreal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接