and I am trying to implement a function that deletes an element from my array and the function does remove the element, but it duplicates the next element in array two times.
1 2 3 4 5 6 7 8 9 10
void SortedList::DeleteItem(ItemType x)
{
for (int i = 0; i < MAX_ITEMS; i++)
{
if (values[i] == x)
{
values[i] = values[i - 1];
}
}
}
List is like this:
1 2 3 4 5 6 7 8 9 10
1
2
3.3
4.4
5.5
6.2
7.1
8
9
10
after deleting 5.5, the output will be like:
1 2 3 4 5 6 7 8 9 10 11
1
2
3.3
4.4
4.4
6.2
7.1
8
9
10
Length is: 10
see that 4.4? I don't want two of them! I just want one.
Try implementing a for loop that shifts all elements to the left after deleting the object. Here is an example of some code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
int rotateLeft(string a[], int n, int pos)
{
if (n < 0 || pos < 0 || pos >= n)
return -1;
// save the element that is to be moved
string toBeMoved = a[pos];
// shift left the elements that are after the one to be moved
for (int k = pos; k < n-1; k++)
a[k] = a[k+1];
// place the moved element at the end
a[n-1] = toBeMoved;
return pos;
}
Except instead of placing the moved element at the end, just leave that segment out.
Its an example from an array that uses strings instead of ints. Yours wouldnt need n, pos is just the position of the element in the array that you are deleting
void SortedList::DeleteItem(int& a[], int x)
{
for (int i = 0; i < MAX_ITEMS; i++)
{
if (values[i] == x)
{
for (int k = i; k < MAX_ITEMS; k++)
{
a[k] = a[k+1];
{
}
}
}