70 lines
4.9 KiB
MQL5
70 lines
4.9 KiB
MQL5
//+------------------------------------------------------------------+
|
|
//| sort_object_ptrs_array.mq5 |
|
|
//| Copyright © 2018, Amr Ali |
|
|
//| https://www.mql5.com/en/users/amrali |
|
|
//+------------------------------------------------------------------+
|
|
#include "Introsort.mqh"
|
|
|
|
//+------------------------------------------------------------------+
|
|
//| Templated class |
|
|
//+------------------------------------------------------------------+
|
|
template <typename T>
|
|
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 <typename T>
|
|
bool CompareByPayload(T left, T right)
|
|
{
|
|
return left.Payload() < right.Payload();
|
|
}
|
|
|
|
// Define multiple pointer types to custom Less function.
|
|
typedef bool (*pLessInt) (Foo<int>*, Foo<int>*);
|
|
typedef bool (*pLessFloat) (Foo<float>*, Foo<float>*);
|
|
|
|
//+------------------------------------------------------------------+
|
|
//| |
|
|
//+------------------------------------------------------------------+
|
|
void OnStart()
|
|
{
|
|
Foo<int> *objArray1[7]; // array of object pointers
|
|
Foo<float> *objArray2[7];
|
|
|
|
//--- Generate random data.
|
|
for(int i = 0; i < 7; i++)
|
|
{
|
|
objArray1[i]=new Foo<int>();
|
|
objArray2[i]=new Foo<float>();
|
|
}
|
|
|
|
//--- Sort the input arrays in-place using a pointer to comparison function less.
|
|
Introsort(objArray1, (pLessInt)CompareByPayload<Foo<int>*>);
|
|
Introsort(objArray2, (pLessFloat)CompareByPayload<Foo<float>*>);
|
|
|
|
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];
|
|
}
|
|
|
|
}
|
|
//+------------------------------------------------------------------+
|