Reputation: 175
I am hoping a fresh set of eyes can help me find what I am doing wrong. I am trying to search an array for a certain int and once it finds it, it will delete it and shift the remaining elements over to fill in where the "deletion" is.
This would be used on a class obj like A.remove(25) where the obj A contains some vars such as Num (the number of elements in the array), Cap (total capacity of the array), and Pool[] (which contains all of the numbers).
bool Set::remove(int X)
{
for(unsigned J=0; J<Num; J++)
{
if(Pool[J] == X)
{
for(unsigned Z=J; J<Num; Z++)
{
if(Z == (Num-1))
{
Pool[Z] = NULL;
}
else
{
Pool[Z] = Pool[Z+1];
}
}
return true;
}
}
return false;
}
Upvotes: 0
Views: 344
Reputation: 47269
In your inner for loop:
for(unsigned Z=J; J<Num; Z++)
The loop condition should be Z<Num
instead of J<Num
:
for(unsigned Z=J; Z<Num; Z++)
Otherwise J<Num
will keep evaluating to true and Z
will be incremented until it's out of bounds of Pool
Upvotes: 4