operator==,!=,<,<=,>,>=,<=>(std::pair)
來自 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) 使用 operator< 按字典序比較 lhs 和 rhs,即比較第一個元素,僅當它們相等時才比較第二個元素。如果 lhs.first < rhs.first、rhs.first < lhs.first 或 lhs.second < rhs.second 的型別和值類別不滿足 BooleanTestable 要求,則行為未定義。
7) 使用 synth-three-way 按字典序比較 lhs 和 rhs,即比較第一個元素,僅當它們相等時才比較第二個元素。synth-three-way-result 是
synth-three-way
的返回型別。
|
(C++20 起) |
目錄 |
[編輯] 引數
lhs, rhs | - | 要比較的 pair |
[編輯] 返回值
1) 如果 lhs.first == rhs.first 和 lhs.second == rhs.second 都為真,則返回 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 定義的,它如果可能則使用 operator<=>,否則使用 operator<。 值得注意的是,如果元素型別本身不提供 operator<=>,但可以隱式轉換為三向可比較型別,則將使用該轉換而不是 operator<。 |
(C++20 起) |
特性測試宏 | 值 | 標準 | 特性 |
---|---|---|---|
__cpp_lib_constrained_equality |
202403L |
(C++26) | std::pair 的受限 operator== |
[編輯] 示例
由於 operator< 為 pair 定義,因此 pair 的容器可以排序。
執行此程式碼
#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++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
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) |
按字典序比較 tuple 中的值 (函式模板) |