Namaran

Code daily. Without assist.

2026-09-30

events.cpp

struct Event {
    int time;
    std::string name;
};

struct ByTime {
    bool operator()(const Event& a, const Event& b) const {
    }
};

std::set<Event, ByTime> が予定を time の早い順に並べるよう、ByTime の operator() を書いてください。time が同じ予定は name の辞書順に並べ、time も name も同じ予定だけを重複として1つにまとめます。出力例は、できた set を先頭から並べたものです。

入力例 1

std::set<Event, ByTime>{{2, "b"}, {1, "z"}, {2, "a"}}

出力例 1

{1, "z"} {2, "a"} {2, "b"}

入力例 2

std::set<Event, ByTime>{{1, "a"}, {1, "a"}}

出力例 2

{1, "a"}

入力例 3

std::set<Event, ByTime>{{3, "x"}, {0, "y"}}

出力例 3

{0, "y"} {3, "x"}
Reference
    bool operator()(const Event& a, const Event& b) const {
        return std::tie(a.time, a.name) < std::tie(b.time, b.name);
    }

std::set は、comp(a, b) と comp(b, a) がどちらも偽になる2つの要素を同じものとして扱い、後から来た方を入れません。a.time < b.time だけを返すと、時刻が同じで名前の違う予定もこの条件を満たすので、例1の {2, "a"} は入らずに消えます。

std::tie は引数への参照を std::tuple にまとめ、< は先頭の要素から順に比べます。time が等しいときだけ name の比較に進むので、等価になるのは両方が等しい予定だけです。掲載したのは参考実装で、唯一の正解ではありません。a.time != b.time ? a.time < b.time : a.name < b.name と書いても同じ順序になります1。

  1. C++20 からは、Event に auto operator<=>(const Event&) const = default; と書けば、メンバを宣言の順に比べる比較演算子が作られます。比較関数を渡さずに std::set<Event> と書いても、同じ並びになります。