On opCmp

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Feb 27 07:00:35 PST 2015


On 2/27/15 6:04 AM, "Nordlöw" wrote:
> Is there a more compact way to describe the opCmp function in the
> following struct
>
> struct Hit
> {
>      size_t count; // number of walkers that found this node
>      NWeight rank; // rank (either minimum distance or maximum strength)
>
>      auto opCmp(const Hit rhs) const
>      {
>          if      (this.count < rhs.count)
>          {
>              return -1;
>          }
>          else if (this.count > rhs.count)
>          {
>              return +1;
>          }
>          else
>          {
>              if      (this.rank < rhs.rank)
>              {
>                  return -1;
>              }
>              else if (this.rank > rhs.rank)
>              {
>                  return +1;
>              }
>              else
>              {
>                  return 0;
>              }
>          }
>      }
> }

Hm... what about:

return count < rhs.count ? -1 : count > rhs.count ? 1 : rank < rhs.rank 
? -1 : rank > rhs.rank;

> by reusing something like
>
>      auto opCmp(const Hit rhs) const
>      {
>          if      (this.count < rhs.count)
>          {
>              return -1;
>          }
>          else if (this.count > rhs.count)
>          {
>              return +1;
>          }
>          else
>          {
>              return this.rank.standardOpCmp(rhs.rank)
>          }
>      }

A standard opCmp would be nice. Why wouldn't you use it for count as well?

-Steve



More information about the Digitalmars-d-learn mailing list