ぺんぎんメモ

プログラミングのメモです。たまに私生活のことや鬱っぽいことを書きます。

Comparableな構造体の定義

次のようなコードをエディタのスニペットに登録しておくと楽。

struct $1 {
  $2
  bool operator<(const $1 &that) const {
    #define lt(x) if (x != that.x) return x < that.x;
    #define gt(x) if (x != that.x) return x > that.x;
    $0
    #undef gt
    #undef lt
    return false;
  }
  bool operator>(const $1 &that) const {
    return that < *this;
  }
};

この構造体は、ベクタ配列だけでなく優先度付きキューの要素としても使える。setやmapのキーにも使える。

使用例
struct Student {
  string name;
  int height;
  bool operator<(const Student &that) const {
    #define lt(x) if (x != that.x) return x < that.x;
    #define gt(x) if (x != that.x) return x > that.x;
    lt(name) gt(height)
    #undef gt
    #undef lt
    return false;
  }
  bool operator>(const Student &that) const {
    return that < *this;
  }
};