I have the function removing items from position 0, but it won't remove items past that, and I don't know why...does anyone else see the problem? I have a dynamic parallel array in which a distinct number is entered into data[i] and copies of that number are tracked by freq[i] so when I remove one freq[i] is decremented and if freq[i] goes to 0 then the array is shifted to reflect the new smaller array size. Here is what I have so far...
bool IntStore::remOne(int target)
{
for(int i = 0; i < used; i++) //start loop to go through arrays to find target number
{
if (data[i] == target) //if data[i] == target decrease freq[i] by one
{
freq[i]--;
}
if (freq[i] == 0) //if freq[i] == 0 shift array down and resize array
{
for (int j = i; j < used; j++) //start loop to shift array
{
data[j]= data[j+1]; //move data down one
freq[j] = freq[j+1]; //move freq down one
used--; //update used to reflect the removed number
resize (capacity - 1); //resize capactity to reflect the smaller array
}
returntrue; //if a copy has been removed if freq == 0
}
returntrue; //if a copy has been removed
}
returnfalse;//if a copy has not been removed
}
if (data[i] == target) //if data[i] == target decrease freq[i] by one
{
freq[i]--;
//}
if (freq[i] == 0) //if freq[i] == 0 shift array down and resize array
{
for (int j = i; j < used; j++) //start loop to shift array
{
data[j]= data[j+1]; //move data down one
freq[j] = freq[j+1]; //move freq down one
used--; //update used to reflect the removed number
resize (capacity - 1); //resize capactity to reflect the smaller array
}
returntrue; //if a copy has been removed if freq == 0
}
}
if (data[i] == target) //if data[i] == target decrease freq[i] by one
{
freq[i]--;
//}
if (freq[i] == 0) //if freq[i] == 0 shift array down and resize array
{
for (int j = i; j < used; j++) //start loop to shift array
{
data[j]= data[j+1]; //move data down one
freq[j] = freq[j+1]; //move freq down one
resize (capacity - 1); //resize capactity to reflect the smaller array
}
used--; //update used to reflect the removed number
returntrue; //if a copy has been removed if freq == 0
}
}
Did you also want to resize it every time through the loop, or just once?
Does it work as is? I'm guessing the above comment won't necessarily cause a problem, but will
reduce the efficiency. However, I'm also guessing that it still doesn't quite work because it looks
like you've got an off-by-one error inside the loop:
If used = 10, then the valid array indices are 0...9 inclusive. Since the loop on line 10 will execute
from i up to 9 inclusive, lines 12 and 13 appear to access the element at index 10, which is outside
the valid bounds.