LoginSignup
9
7

More than 5 years have passed since last update.

std::set<T>の所属判定をスマートに書く

Posted at

C++ STLで集合を表現するstd::setクラスは、この手のクラスによくあるようなcontainsメソッドのようなものを持っていません。
だから、集合sが要素eを含んでいるかどうかは

s.find(e) != s.end()

と表現します。訓練されたC++使いにはこれがs.contains(e)のように目に飛び込んでくるんでしょうが、一般的に言ってこれは意図とコードが直結していないよろしくない表現です。
だから、ヘッダファイルにこんな演算子オーバーロードを用意しましょう。

/// <summary>std::setの所属判定演算子</summary>
template <typename T>
static bool operator>(const std::set<T>& s, const T& item){
    return s.find(item) != s.end();
}

/// <summary>std::setの所属判定演算子</summary>
template <typename T>
static bool operator<(const T& item, const std::set<T>& s){
    return s > e;
}

演算子オーバーロードにテンプレート使えるんですね。
さてこれを定義しておくと…

s > e
// もしくは
e < s

こう書けます。スマート。数学の⊂記号を演算子に使えたらもっと良かったんでけれど。
std::vector版も置いていきますね。

/// <summary>std::vectorの所属判定演算子</summary>
template <typename T>
static bool operator>(const std::vector<T>& s, const T& item){
    return std::find(s.cbegin(), s.cend(), e) != s.cend();
}

/// <summary>std::vectorの所属判定演算子</summary>
template <typename T>
static bool operator<(const T& item, const std::vector<T>& s){
    return s > e;
}
9
7
6

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
7