How to properly remove an element from an array?

I am creating a list using Arrays

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.

How?
Last edited on
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.
What is n and what is pos? I didn't get your code.
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
1
2
3
4
5
6
7
8
9
10
11
12
13
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];
                       {
		}
	}
}
So you basically copying the left elements to a new array a[k]?

I don't want to pass an array into my function, it's just gonna make the code longer and more complicated.

It would make the other functions in my code need to be changed.

Edit: I figured it out!

this is the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void SortedList::DeleteItem(ItemType x)
{
	for (int i = 0; i < MAX_ITEMS; i++) // loop to find the item to delete
	{
		if (values[i] == x)   // if we find the item to delete
		{
			for (int j = i; j < MAX_ITEMS - 1; j++)
			{
				values[j] = values[j + 1];
			}

			values[MAX_ITEMS - 1] = NULL;
			length--;
			break;
		}
	}
}


Thanks @Mattdrag for the help.
Last edited on
Topic archived. No new replies allowed.