在 C++ 中:如何通过将元素下方的条目向上移动一个来将元素覆盖到数组

In C++: How to overwrite an element to an array by moving entries below it up by one

我正在尝试 "delete" 我数组中的一个元素。那些比我更了解 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],但这并没有给我想要的。

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

将删除元素后的条目移到前面一位。

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

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;
}

这应该可以做到。它将所有元素移动到位并删除您要删除的条目。

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

  --arraySize;