//+------------------------------------------------------------------+ //| sort_object_ptrs_array.mq5 | //| Copyright © 2018, Amr Ali | //| https://www.mql5.com/en/users/amrali | //+------------------------------------------------------------------+ #include "Introsort.mqh" //+------------------------------------------------------------------+ //| Templated class | //+------------------------------------------------------------------+ template class Foo { public: Foo(void) { payload=(T)10*MathRand()/MathRand(); } ~Foo(void) { } T Payload(void) { return payload; } private: T payload; }; //+------------------------------------------------------------------+ //| Templated compare function for different types of payloads. | //+------------------------------------------------------------------+ template bool CompareByPayload(T left, T right) { return left.Payload() < right.Payload(); } // Define multiple pointer types to custom Less function. typedef bool (*pLessInt) (Foo*, Foo*); typedef bool (*pLessFloat) (Foo*, Foo*); //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ void OnStart() { Foo *objArray1[7]; // array of object pointers Foo *objArray2[7]; //--- Generate random data. for(int i = 0; i < 7; i++) { objArray1[i]=new Foo(); objArray2[i]=new Foo(); } //--- Sort the input arrays in-place using a pointer to comparison function less. Introsort(objArray1, (pLessInt)CompareByPayload*>); Introsort(objArray2, (pLessFloat)CompareByPayload*>); Print("Integer objects:"); for(int i = 0; i < 7; i++) { printf("%d. payload=%s",i,(string)objArray1[i].Payload()); delete objArray1[i]; } Print("Float objects:"); for(int i = 0; i < 7; i++) { printf("%d. payload=%s",i,(string)objArray2[i].Payload()); delete objArray2[i]; } } //+------------------------------------------------------------------+