dingmaotu / mql4-lib

MQL4/5 Foundation Library For Professional Developers
Apache License 2.0
544 stars 251 forks source link

SortedArray with custom SortComparer #68

Closed mrhoga closed 10 months ago

mrhoga commented 10 months ago

Hello, I'm trying to get a SortedArray with its own type and its own SortComparer to work, but unfortunately I'm failing miserably with the following error message:

'PositionSortComparer' - cannot instantiate abstract class see declaration of class 'PositionSortComparer' 'int EqualityComparer<Position>::hash(const Position) const' is abstract EqualityComparer.mqh 30 14 'int SortComparer<Position>::compare(const Position,const Position*) const' is abstract SortComparer.mqh 36 22

My data class and SortComparer implementation look like this:

class position
{
    public:

       double Size;
       double PNL;
       int Ticket;

       Position(){}

       Position(int ticket, double size, double pnl) : Ticket(ticket), Size(size), PNL(pnl)
       {}

       Position(const Position & other)
       {
          Ticket = other.Ticket;
          Size = other.Size;
          PNL = other.PNL;
       }
};

class PositionSortComparer : public SortComparer<Position*>
{
    public:

       int hash(const Position* value)
       {
          return value.Ticket;
       }

       int compare(const Position* left, const Position* right)
       {
          if (left.Size > right.Size) return 1;
          if (left.Size < right.Size) return -1;
          return 0;
       }

       bool equals(const Position* left, const Position* right)
       {
          return left.Ticket == right.Ticket;
       }
};

// usage
PositionSortComparer* comparer = new PositionSortComparer();
SortedArray<Position*>* sorted = new SortedArray<Position*>(comparer);

What am I doing wrong? I am grateful for any help, best regards mrhoga

dingmaotu commented 10 months ago

I think you forgot to add const after method definitions to match parent method signatures.

class PositionSortComparer : public SortComparer<Position*>
  {
public:

   int               hash(const Position* value) const
     {
      return value.Ticket;
     }

   int               compare(const Position* left, const Position* right) const
     {
      if(left.Size > right.Size)
         return 1;
      if(left.Size < right.Size)
         return -1;
      return 0;
     }

   bool              equals(const Position* left, const Position* right) const
     {
      return left.Ticket == right.Ticket;
     }
  };
mrhoga commented 10 months ago

Thank you, that was actually the problem! I'm still having a hard time with MQL :) By the way, thanks for the great library, it really makes things a lot easier!