I have problem with removing elements from array by value of elements. I create a function which remove elements from array by index, now i want to use this function to remove element of array by value.
Here is my code:
bool Array::RemoveAt(int index)
{
if (index < 0 || index >= number_of_elements)
return false;
for (int i = index; i < this->number_of_elements-1; i )
{
this->arr[i] = this->arr[i 1];
}
this->number_of_elements--;
return true;
}
bool Array::RemoveByValue(int value)
{
for (int i = 0; i < this->number_of_elements-1; i )
{
if (this->arr[i] == value) {
this->RemoveAt(i);
return true;
}
else
return false;
}
}
CodePudding user response:
First of all, when you use this->number_of_elements--;
it doesn't actually make the array smaller, the array is still using x bytes of memory, you just change the integer.
The reason RemoveByValue()
isn't working is because you're returning a false in the first loop iteration. So like, it sees the first element, is it equal to value? No, OK, end the function. You need to move that return false;
out of the loop.
CodePudding user response:
RemoveByValue()
is ignoring the last element in the array. You need to get rid of -1
in that loop.
Also, the return false;
is causing the function to exit prematurely. It needs to be moved outside of the loop.
Try this:
bool Array::RemoveByValue(int value)
{
for (int i = 0; i < this->number_of_elements; i)
{
if (this->arr[i] == value)
{
this->RemoveAt(i);
return true;
}
}
return false;
}
On a side note, I would suggest tweaking the loop in RemoveAt()
to the following:
bool Array::RemoveAt(int index)
{
if (index < 0 || index >= number_of_elements)
return false;
for (int i = index 1; i < this->number_of_elements; i)
{
this->arr[i - 1] = this->arr[i];
}
this->number_of_elements--;
return true;
}