c++ - 从 C++ 中的列表中删除项目

标签 c++ list

我有这个程序,我想在其中插入和删除列表中的项目。我的删除功能有问题。我希望用户告诉我他们想在列表中删除哪个索引,然后减小列表的大小,然后将项目一起移动。 例如: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;
}

最佳答案

就像其他人说的,你应该尝试使用STL。但是使用你到目前为止的代码。您应该将您的 for 更改为这样的内容:

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

}

这样做的目的是,从删除的项目开始,将每一项替换为后面的一项。这就像向左移动。

这不会破坏任何元素,但我猜我们可以放手。

关于c++ - 从 C++ 中的列表中删除项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13167011/

相关文章:

c++ - 如何构建捕获所有异常的 C++ Dll 包装器?

c# - 如何在 C# 中将嵌套列表转换为数据集

html - 我对这些无序列表做错了什么?

c++ - 为什么在尝试实现此动态数组时会出现 EXC BAD ACCESS 错误?

C++ - 创建数组的低通滤波器函数

list - 映射列表时是否在每次迭代后释放内存?

python - 有没有一种更优雅的方法可以将字典的键和值解包到两个列表中,而又不会失去一致性?

java - 如何在java中动态创建列表而不重复?

c++ - 如何配置项目的 CMakeLists.txt 文件以在 Qt Creator 中将项目分开而不是一个项目

c++ - 类赋值运算符=问题