最終更新日時:
が更新

履歴 編集

function template
<utility>

std::pair::operator<=>

namespace std {
  template <class T1, class T2>
  struct pair {
    friend constexpr common_comparison_category_t<synth-three-way-result<T1>, synth-three-way-result<T2>>
       operator<=>(const pair& x, const pair& y);                       // (1) C++20
  };

  template <class T1, class T2, class U1, class U2>
  constexpr common_comparison_category_t<synth-three-way-result<T1, U1>, synth-three-way-result<T2, U2>>
     operator<=>(const pair<T1, T2>& x, const pair<U1, U2>& y);         // (2) C++23
}

概要

2つのpairの三方比較を行う。

  • (1) : 同じ型のpair同士の三方比較を行う。
  • (2) : 左辺と右辺で要素型が異なるpair同士の三方比較を行う。

効果

以下と等価:

if (auto c = synth-three-way(x.first, y.first); c != 0)
  return c;
return synth-three-way(x.second, y.second);

備考

  • この演算子により、以下の演算子が使用可能になる (C++20):
    • operator<
    • operator<=
    • operator>
    • operator>=
  • (2) : C++23で追加された。これにより、referencepair<T&, U&>value_typepair<T, U>となるような(views::zip相当の)Rangeをranges::sortなどでソートできるようになる。

#include <cassert>
#include <utility>
#include <string>

int main()
{
  std::pair<int, std::string> p1(1, "aaa");
  std::pair<int, std::string> p2(1, "aaa");
  std::pair<int, std::string> p3(2, "bbb");

  assert((p1 <=> p2) == 0);
  assert((p1 <=> p3) != 0);
  assert(p1 < p3);
  assert(p1 <= p3);
  assert(p3 > p1);
  assert(p3 >= p1);
}

出力

参照