【问题标题】:MQL4/5 CList Search method always returning null pointerMQL4/5 CList 搜索方法总是返回空指针
【发布时间】:2020-01-07 19:53:07
【问题描述】:

我正在尝试在应用程序中使用 CList Search 方法。我在下面附上了一个非常简单的例子。 在这个例子中,我总是在变量result 中得到一个空指针。我在 MQL4 和 MQL5 中尝试过。有没有人使搜索方法工作?如果是这样,我的错误在哪里?关于我的问题,我指的是 this MQL 中链表的实现(它是标准实现)。当然,在我的应用程序中,我不想找到第一个列表项,而是要找到符合特定条件的项。但即使是这个微不足道的例子也不适合我。

#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;
}

【问题讨论】:

    标签: pointers mql4 mql5 clist


    【解决方案1】:

    CList是一种链表。一个经典的数组列表是 MQL4/5 中的 CArrayObjSearch() 和一些其他方法。在调用搜索之前,您必须对列表进行排序(因此实现 virtual int Compare(const CObject *node,const int mode=0) const 方法)。

    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);
    }
    

    【讨论】:

    • 感谢您的回答。你的答案有参考资料吗?
    • 您需要什么样的参考资料?
    • 为什么我必须先对列表进行排序才能在其中搜索?没有其他语言会产生这种开销!?
    • 您可以进行线性搜索,或排序并应用快速搜索。 Search() 是快速机制的实现,这就是为什么你需要先排序。打开CArrayObj.mqh的源码,看看它是如何实现的,了解为什么需要排序。
    • 嗨丹尼尔你的答案没有运行。错误:“虚拟”-意外令牌
    猜你喜欢
    • 1970-01-01
    • 2016-12-09
    • 1970-01-01
    • 2013-02-23
    • 1970-01-01
    • 2022-11-14
    • 1970-01-01
    • 1970-01-01
    • 2015-09-18
    相关资源
    最近更新 更多