operator==,!=,<,<=,>,>=,<=>(std::pair)
From cppreference.com
| ヘッダ <utility> で定義 |
||
| (1) | ||
| (C++14まで) | ||
| (C++14以降) | ||
| (2) | ||
| (C++14まで) | ||
| (C++14以降) (C++20まで) |
||
| (3) | ||
| (C++14まで) | ||
| (C++14以降) (C++20まで) |
||
| (4) | ||
| (C++14まで) | ||
| (C++14以降) (C++20まで) |
||
| (5) | ||
| (C++14まで) | ||
| (C++14以降) (C++20まで) |
||
| (6) | ||
| (C++14まで) | ||
| (C++14以降) (C++20まで) |
||
| template< class T1, class T2, class U1, class U2 > constexpr std::common_comparison_category_t<synth-three-way-result<T1, U1>, |
(7) | (C++20以降) |
1,2) lhs と rhs の両方の要素が等しいかどうかをテストする。つまり、lhs.first と rhs.first、および lhs.second と rhs.second を比較する。
|
lhs.first == rhs.first または lhs.second == rhs.second のいずれかの型と値カテゴリが BooleanTestable の要件を満たさない場合、動作は未定義となる。 |
(C++26まで) |
|
このオーバーロードは、decltype(lhs.first == rhs.first) と decltype(lhs.second == rhs.second) の両方が |
(C++26以降) |
3-6) lhs と rhs を operator< で辞書式に比較する。つまり、最初の要素を比較し、それらが等しい場合にのみ、2番目の要素を比較する。lhs.first < rhs.first、rhs.first < lhs.first、または lhs.second < rhs.second のいずれかの型と値カテゴリが BooleanTestable の要件を満たさない場合、動作は未定義となる。
7) lhs と rhs を synth-three-way で辞書式に比較する。つまり、最初の要素を比較し、それらが等しい場合にのみ、2番目の要素を比較する。synth-three-way-result は
synth-three-way の戻り値の型である。|
|
(C++20以降) |
目次 |
[編集] パラメーター
| lhs, rhs | - | 比較するペア |
[編集] 戻り値
1) lhs.first == rhs.first と lhs.second == rhs.second の両方が true の場合、true。それ以外の場合は false。
2) !(lhs == rhs)
3) lhs.first < rhs.first の場合、true を返す。そうでない場合、rhs.first < lhs.first の場合、false を返す。そうでない場合、lhs.second < rhs.second の場合、true を返す。それ以外の場合は false を返す。
4) !(rhs < lhs)
5) rhs < lhs
6) !(lhs < rhs)
7) synth-three-way(lhs.first, rhs.first) が 0 と等しくない場合、それを返す。そうでなければ synth-three-way(lhs.second, rhs.second) を返す。
[編集] 備考
|
関係演算子は、各要素の operator< を用いて定義される。 |
(C++20まで) |
|
関係演算子はsynth-three-wayを介して定義されます。synth-three-wayは、可能であればoperator<=>を使用し、そうでなければoperator<を使用します。 特に、要素の型がそれ自体 operator<=> を提供しないが、三方比較可能な型に暗黙的に変換できる場合、operator< の代わりにその変換が使用される。 |
(C++20以降) |
| 機能テストマクロ | 値 | 規格 | 機能 |
|---|---|---|---|
__cpp_lib_constrained_equality |
202403L |
(C++26) | std::pair の制約付き operator== |
[編集] 例
ペアに対して operator< が定義されているため、ペアのコンテナをソートできる。
このコードを実行
#include <algorithm> #include <iomanip> #include <iostream> #include <string> #include <utility> #include <vector> int main() { std::vector<std::pair<int, std::string>> v = {{2, "baz"}, {2, "bar"}, {1, "foo"}}; std::sort(v.begin(), v.end()); for (auto p : v) std::cout << '{' << p.first << ", " << std::quoted(p.second) << "}\n"; }
出力
{1, "foo"}
{2, "bar"}
{2, "baz"}[編集] 欠陥報告
以下の動作変更を伴う欠陥報告が、以前に公開されたC++標準に遡って適用されました。
| DR | 適用対象 | 公開された動作 | 正しい動作 |
|---|---|---|---|
| LWG 296 | C++98 | == と < 以外の演算子の記述が欠落していた |
追加された |
| LWG 2114 (P2167R3) |
C++98 | ブール演算の型事前条件が欠落していた | 追加された |
| LWG 3865 | C++98 | 比較演算子は、同じ型の pair のみを受け入れていた |
異なる型の pair を受け入れる |
[編集] 関連項目
| (C++20で削除)(C++20で削除)(C++20で削除)(C++20で削除)(C++20で削除)(C++20) |
タプル内の値を辞書順に比較する (関数テンプレート) |