Page 1 of 1

Coding - Iterate & Delete

Posted: Sat Sep 17, 2005 10:04 pm
by va!n
nice article and example by chaos/farbrausch, talking about iterate and deleting elements of an array... here we go...



Imagine you have an array of elements that you want to process. While processing, you might find out that one element should be deleted. The usual problem is how to delete an object out of an array without having to leave the iteration. I assume that I may change the order of elements.

I found a simple loop that does the trick, and I find it so elegant that I want to put it on my webpage:

Code: Select all

/****************************************************************************/

struct Element                      // some data structure
{
  sInt Data;
  sInt MoreData;
  sInt UseLessData;
  sInt Select;                      // Select flag for user interface
};

/****************************************************************************/

struct Element *Array;              // This is a dynamic array :-)
sInt Count;

/****************************************************************************/

void DeleteSelected()               // delete all selected elements
{                                   // do not preserve order
  sInt i;
  
  for(i=0;i<Count;)              // NOTE: i is not incremented
  {
    if(Array[i].Select)             // if selected
    {
      Count--;
      Array[i] = Array[Count];      // copy last element over current
    }
    else                            // else
    {
      i++;                          // go to next element
    }
  }
}

/****************************************************************************/
This loop terminates because either i increases or Count decreases with every iteration.