MQL4/5 CList Search method always returning null pointer

959 views Asked by At

I'm trying to use the CList Search method in an application. I have attached a very simple example below. In this example, I always get a null pointer in the variable result. I tried it in MQL4 and MQL5. Has anyone ever made the Search method work? If so, where is my mistake? With my question, I refer to this implementation of a linked list in MQL (it's the standard implementation). Of course, in my application, I do not want to find the first list item, but items that match specific criteria. But even this trivial example does not work for me.

#property strict
#include <Arrays\List.mqh>
#include <Object.mqh>

class MyType : public CObject {
   private:
      int val;
   public:
      MyType(int val);
      int GetVal(void);   
};
MyType::MyType(int val): val(val) {}
int MyType::GetVal(void) {
   return val;
}

void OnStart() {
   CList *list = new CList();
   list.Add(new MyType(3));

   // This returns a valid pointer with
   // the correct value
   MyType* first = list.GetFirstNode();

   // This always returns NULL, even though the list
   // contains its first element
   MyType* result = list.Search(first);

   delete list;
}
1

There are 1 answers

6
Daniel Kniaz On BEST ANSWER

CList is a kind of linked list. A classical arraylist is CArrayObj in MQL4/5 with Search() and some other methods. You have to sort the list (so implement virtual int Compare(const CObject *node,const int mode=0) const method) before calling search.

virtual int       MyType::Compare(const CObject *node,const int mode=0) const {
  MyType *another=(MyType*)node;
  return this.val-another.GetVal();
}

void OnStart(){
  CArrayObj list=new CArrayObj();
  list.Add(new MyType(3));
  list.Add(new MyType(4));
  list.Sort();

  MyType *obj3=new MyType(3), *obj2=new MyType(2);
  int index3=list.Search(obj3);//found, 0
  int index2=list.Search(obj2);//not found, -1
  delete(obj3);
  delete(obj2);
}