Those who know javascript or python will likely recognize this pattern immediately.
This is a generic object vector (CArrayObj subclass) that I frequently use in MQL programming, and I've added a filter method which takes a function as an argument and returns a pointer to the new (filtered) vector. The new vector is added to a "garbage collector" so there is no need for memory management, however, if the scope of the original (non-filtered) collection runs out before the scope of the filtered vector then there will be an error due to the object getting destroyed.
objvector and function pointer declaration
Using filter in some interesting ways.
This is a generic object vector (CArrayObj subclass) that I frequently use in MQL programming, and I've added a filter method which takes a function as an argument and returns a pointer to the new (filtered) vector. The new vector is added to a "garbage collector" so there is no need for memory management, however, if the scope of the original (non-filtered) collection runs out before the scope of the filtered vector then there will be an error due to the object getting destroyed.
objvector and function pointer declaration
Inserted Code
#include <arrays/arrayobj.mqh> typedef bool (*FilterFunc)(CObject*); template <typename T> class objvector : public CArrayObj { protected: CArrayObj m_garbage_collector; public: T operator[](const int index)const{return this.At(index);} objvector<T>* filter(FilterFunc func) { objvector<T>* new_vector = new objvector<T>(); m_garbage_collector.Add(new_vector); new_vector.FreeMode(false); int size = this.Total(); for (int i=0; i<size; i++) if (func(this[i])) new_vector.Add(this[i]); return new_vector; } };
Using filter in some interesting ways.
Inserted Code
class Trade : public CObject { public: int ticket; double profit; Trade(int _ticket) { if (OrderSelect(_ticket, SELECT_BY_TICKET)) { ticket = _ticket; profit = OrderProfit(); } } }; bool fWin(CObject *obj) { return ((Trade*)obj).profit > 0; } bool fLose(CObject *obj) { return ((Trade*)obj).profit < 0; } bool fSymbol(CObject *obj) { return (OrderSelect(((Trade*)obj).ticket, SELECT_BY_TICKET) && OrderSymbol() == _Symbol); } void OnStart() { objvector<Trade*> all, *winners, *losers, *my_symbol_losers; for (int i=0; OrderSelect(i, SELECT_BY_POS, MODE_HISTORY); i++) all.Add(new Trade(OrderTicket())); winners = all.filter(fWin); losers = all.filter(fLose); my_symbol_losers = losers.filter(fSymbol); printf("winners=%d, losers=%d, all=%d", winners.Total(), losers.Total(), all.Total()); }