c++ - 在 C++ 中 : How to overwrite an element to an array by moving entries below it up by one

标签 c++ arrays overwrite

我正在尝试“删除”数组中的一个元素。那些比我更了解 C++ 的人告诉我,要完成此操作,我必须将所有条目移动到我要删除的条目下方 1。之后,我必须将跟踪数组大小的变量减少 1 .所以我写了这段代码来实现这一点:

cout << "Type the number of the inventory entry you would like to delete:\n";
        cin >> entryToDelete;

        for ( count = 0 ; count < (entryToDelete - 1) ; count++)
                list[count] = list[count + 1];

position--;

我之前为用户显示数组中的条目为 #1、#2、#3 等,而它们的下标为 0、1、2 等...这就是我放置 entryToDelete - 1 的原因. position是跟踪数组大小的变量。不管怎样,我使用这段代码来输出数组,这样我就可以检查代码是否有效:

for (int count = 0 ; count <= position ; count++)
        {
                cout << "Entry #" << (count + 1) << endl;
                cout << "ISBN: " << list[count].ISBN << endl
                     << "Author: " << list[count].Author << endl
                     << "Title: " << list[count].Title << endl
                     << "Quantity: " << list[count].Quantity << endl
                     << "Price: " << list[count].Price << endl << endl;
        }

由于某种原因,无论我输入什么数字来删除,数组中的最后一个元素都被删除了。我尝试了几种修改,例如更改要修改的数组元素的顺序:即list[count + 1] = list[count] ,但这并没有给我想要的东西。

不幸的是,我被限制使用 vector 。

最佳答案

您需要将该元素右侧的所有元素向左移动一个。

enter image description here

Here是一个简单的代码,展示了如何向左移动元素

#include <iostream>
using namespace std;

int main() {
    int arr[10]=  {0,1,2,3,4,5,6,7,8,9};
    int numToDelete = 5;

    for (int i = numToDelete; i < sizeof(arr)/sizeof(arr[0]); i++ )
    {
        arr[i] = arr[i+1];
    }

    arr[sizeof(arr)/sizeof(arr[0]) - 1] = 0;

    for(int i = 0; i < sizeof(arr)/sizeof(arr[0]); i++)
    {
        cout << arr[i] << endl;
    } 

    return 0;
}

关于c++ - 在 C++ 中 : How to overwrite an element to an array by moving entries below it up by one,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29464690/

相关文章:

c++ - 将二维数组作为指向整数数组的指针传递给函数

c++ - 如何在 C++ 中编写缓存友好的多态代码?

javascript - 从嵌套的 JSON 数组中获取数据

在 foreach 循环中使用 array_combine 时 PHP 内存耗尽

linux - 在 Linux 中以编程方式创建的文件变为 NULL

c++ - 使用插槽创建对话框

c++ - C++ 的双对数函数的实现?

python - 如何在 python3 中有效地将位从一个字节数组打包到另一个字节数组?

tar - 'tar --overwrite'实际做什么(或不做什么)?

Python:用更少的变量写一个新列表