Sorting dynamic arrays with a function problem?

//================================================================
// Remove items/s
//================================================================
void ItemGen::removeItem()
{
for(int i=_itemCount;i>0;--i) //start the check at the top of the array moving down
{
if(_items[i].getStatus() == "remove") // checks status and executes if = "remove"
{
for(int j = i; j<_itemCount;++j) // starts at point on array remove is found and counts up
{
_items[j] = _items[j+1]; // copying down 1 until end of array is reached
}
_itemCount--; // -1 from array
} //performs process again until no "remove"s are found
}
}

I want to start from the top of the array and move down checking each item, if the items status = "remove" then I want to copy all the data above in the array down 1, and then -1 from '_itemCount' the number of items in the array.

This function isn't working and I'm not sure why?...

Please help :D

Last edited on
Please use code tags.

First, make a check array function
Second, make a copy array function
Third, make a remove character function

Then come back with entire program (placed in code tags) and maybe everybody will be happier.
I'm trying to copy the data down by doing:

for(int j = i; j<_itemCount;++j) // moves up 1 on the array where "remove" was found then
{
_items[j] = _items[j+1];// copies data down 1 each time it moves up 1
}

Do I have to create 'new' objects to add to my existing array or do I make another array to copy to?

thanks.

p.s added code tags above.
Last edited on
Difficult to diagnose without seeing the class declaration for ItemGen.
However a couple of things are obvious:
1) Assuming _itemCount is the number of items in the array, the following statement is going to index past the end of the array on the first pass through the loop:
 
if(_items[i].getStatus() == "remove")

2) Your second loop is also going to start past the end of the array.

PLEASE USE CODE TAGS (the <> formatting button) when posting code.
You are the boss it needed to be.. _items[i - 1].

I'll use the tags next time I didn't know about them.
much respect ;)

thanks.

1
2
3
4
for(int j = i;j < _itemsCount;j++,i--)
{
      _items[i] = _items[j];
}
@greenleaf
1
2
3
for(int j = i;j < _itemsCount;j++,i--)
{   _items[i] = _items[j];
}

That's not going to work. Let's assume item[5] is to be removed. The first iteration of the loop, both i and j are 5 resulting in item[5] overwriting itself, essentially a noop but poor practice. Second iteration of the loop item[6] overwrites item[4]. Not what we want. You want item[6] to overwrite item[5] continuing until all remaining items have been moved.
Last edited on
Topic archived. No new replies allowed.