Reputation: 2051
I am trying to "delete" an element in my array. I have been told by those who know C++ better than I do that to accomplish this I must move all entries below the one I want to delete up by 1. Afterwards, I must decrease by 1 the variable keeping track of the size of the array. So I wrote this code to accomplish that:
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--;
I previously displayed for the user the entries in the array as #1, #2, #3, etc while their subscripts are 0, 1, 2, etc... That is why I put entryToDelete - 1
. position
is the variable that keeps track of the size of the array. Anyway, I use this code to output the array so I can check if the code worked:
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;
}
For some reason, no matter what number I input to delete, the last element in the array is deleted. I have tried several modifications, such as changing the order of the array elements to modify: i.e. list[count + 1] = list[count]
, but this does not give me what I want.
Unfortunately, I am restricted from using vectors.
Upvotes: 0
Views: 1455
Reputation: 1765
This should do it. It moves all the elements into place and removes the entry you wanted to delete.
for ( size_t count = entryToDelete; count < arraySize - 1 ; ++count)
list[count] = list[count + 1];
--arraySize;
Upvotes: 1
Reputation: 2033
You need to move all elements to the right of that element one to the left.
Here is a simple code that shows how to move elements to the left
#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;
}
Upvotes: 2
Reputation: 31647
Move the entries following the deleted element to the front by one.
Upvotes: 1