What is the correct way to fill an array with Positions?

 

The code: 

   void              FillArray(PosArray& C)
     {
      int total=PositionsTotal();
      for(int i=0; i<total; i++)
        {
         CPositionInfo p;
         if(p.SelectByIndex(i))
           {
            C.InsertSort(new Pos(p));
           }
        Sleep(1);
        }
      }

The problem is that the PositionsTotal can change while this code is running. "Sleep" is there to fake some longer calculations. This is not necessary but increases the chances of getting false data. 

Let's say we start with PositionsTotal=2 and the first position with index=0 is in the process of closing. 

So, in the for loop's first cycle the closing position is still there at index=0 but after the first cycle's long calculation the PositionsTotal decreases and the position that was originally at index=1, now is at index=0 and the second cycle's SelectByIndex (at 1) will fail. Which means we end up with an array that stores the closed position and misses the valid open position. 

 
Count down instead of up.
 
Enrique Dangeroux #:
Count down instead of up.
You would get two copies of the second position in that case. Resizing the array would fix that. Is that the most elegant (and reliable) way?