MQL4 prepend value to array

 

Hi there,

 

This is my first post, so I hope its gonna make any sense :) 

 

How can I have a reversed Array (like a timeseries), and prepend a new element into the Array and throw the last one out (if over max-length).

 So Array[0] is the newest value and Array[49] is the last value..

I tried like this ->

 

double myArray = []; // Dynamic array
extern int maxArrayLength = 50;
bool prependToReversedDoubleArray(double& theArray[], double value, int maxLength) {
   
   int size = ArraySize(theArray);
   
   // Normalize the array (left to right)
   ArraySetAsSeries(theArray, false);
   
   // Extend array length
   ArrayResize(theArray, size+1);
   
   Alert("test = ", size);
   
   // Insert the new value
   theArray[size] = value;
   
   // Reverse the array again
   ArraySetAsSeries(theArray, true);
   
   if (ArraySize(theArray) > maxLength) {
      ArrayResize(theArray, maxLength);
   }
   
   return(true);
}
prependToReversedDoubleArray(myArray, 0.1234, maxArrayLength)

 

 But it will always Alert the array has a length of 2 :s 

 Alert("test = ", size); // 2

 Why is it so damn hard to create an Array :(

 
Your code as written is correct.
 

That is very nice to hear indeed :p Thanks

 

But it does give problems, like length is always 2..

 

The length should be growing until [maxArrayLength] 50.. Do you have any idea why it never gets longer then 2?

 

Thanks! 

 
DutchKevv: Do you have any idea why it never gets longer then 2?
There are no mind readers here. The posted code is correct. Therefor the problem is elsewhere.
 
WHRoeder:
DutchKevv: Do you have any idea why it never gets longer then 2?
There are no mind readers here. The posted code is correct. Therefor the problem is elsewhere.

Roger. 

 

Thanks for reviewing the code.. Good to know i'm on the right track. 

 

Thanks 

 
double myArray = []; // Dynamic array

I don't know how your code could compile

should be

double myArray[]; // Dynamic array

 As WH says, problem is elsewhere. You are probably either modifying the value of maxArrayLength or resizing the array in another section of code.

 

Hi @GumRai, 

 

You are correct, it wasn't part of the code, I just typed it for this Forum post..

 

Anyway, it is fixed :) @WHRoeder, you were right to. The problem was somewhere else.. The code worked fine.

 This is the final code I use ->

 

int prependToReversedDoubleArray(double &theArray[],double value,int maxLength) 
  {

   int newSize=ArraySize(theArray)+1;

// Normalize the array (left to right)
   ArraySetAsSeries(theArray,false);

// Extend array length
   ArrayResize(theArray,newSize);

// Insert the new value
   theArray[newSize-1]=value;

// Reverse the array again
   ArraySetAsSeries(theArray,true);

// Check if the max length is reached
   if(maxLength>0 && newSize>maxLength) 
     {
      ArrayResize(theArray,maxLength);
      newSize=maxLength;
     }

   return(newSize);
  }

 

Thanks! 

Reason: