operator==,!=,<,<=,>,>=,<=>(std::map)
來自 cppreference.com
| 定義於標頭檔案 <map> |
||
| (1) | ||
| (2) | (C++20 前) | |
| (3) | (C++20 前) | |
| (4) | (C++20 前) | |
| (5) | (C++20 前) | |
| (6) | (C++20 前) | |
| (7) | (C++20 起) | |
比較兩個 map 的內容。
1,2) 檢查 lhs 和 rhs 的內容是否相等,即它們擁有相同數量的元素,並且 lhs 中的每個元素與 rhs 中相同位置的元素比較相等。
7) 按字典序比較 lhs 和 rhs 的內容。比較的執行如同呼叫 std::lexicographical_compare_three_way(lhs.begin(), lhs.end(),
rhs.begin(), rhs.end(), synth-three-way)。此比較忽略 map 的排序 Compare。 如果以下條件均不滿足,則行為未定義
-
T滿足three_way_comparable。 - 為型別(可能 const 限定的)
T的值定義了<,並且<是全序關係。
|
|
(C++20 起) |
目錄 |
[編輯] 引數
| lhs, rhs | - | 要比較其內容的 map。 |
-T, Key 必須滿足 EqualityComparable 的要求,才能使用過載 (1,2)。 | ||
-Key 必須滿足 LessThanComparable 的要求,才能使用過載 (3-6)。排序關係必須建立全序。 | ||
[編輯] 返回值
1) 如果
map 的內容相等,則為 true,否則為 false。2) 如果
map 的內容不相等,則為 true,否則為 false。3) 如果 lhs 的內容按字典序*小於* rhs 的內容,則為 true,否則為 false。
4) 如果 lhs 的內容按字典序*小於或等於* rhs 的內容,則為 true,否則為 false。
5) 如果 lhs 的內容按字典序*大於* rhs 的內容,則為 true,否則為 false。
6) 如果 lhs 的內容按字典序*大於或等於* rhs 的內容,則為 true,否則為 false。
7) 如果存在非等價元素對,則為 lhs 和 rhs 中第一對非等價元素的相對順序,否則為 lhs.size() <=> rhs.size()。
[編輯] 複雜度
1,2) 如果 lhs 和 rhs 的大小不同,則為常量時間,否則與
map 的大小呈線性關係。3-7) 與
map 的大小呈線性關係。[編輯] 註解
|
關係運算符是根據元素型別的 operator< 定義的。 |
(C++20 前) |
|
關係運算符透過 synth-three-way 定義,如果可能則使用 operator<=>,否則使用 operator<。 值得注意的是,如果元素本身不提供 operator<=>,但可以隱式轉換為三向可比較型別,則將使用該轉換而不是 operator<。 |
(C++20 起) |
[編輯] 示例
執行此程式碼
#include <cassert> #include <compare> #include <map> int main() { std::map<int, char> a{{1, 'a'}, {2, 'b'}, {3, 'c'}}; std::map<int, char> b{{1, 'a'}, {2, 'b'}, {3, 'c'}}; std::map<int, char> c{{7, 'Z'}, {8, 'Y'}, {9, 'X'}, {10, 'W'}}; assert ("" "Compare equal containers:" && (a != b) == false && (a == b) == true && (a < b) == false && (a <= b) == true && (a > b) == false && (a >= b) == true && (a <=> b) != std::weak_ordering::less && (a <=> b) != std::weak_ordering::greater && (a <=> b) == std::weak_ordering::equivalent && (a <=> b) >= 0 && (a <=> b) <= 0 && (a <=> b) == 0 && "Compare non equal containers:" && (a != c) == true && (a == c) == false && (a < c) == true && (a <= c) == true && (a > c) == false && (a >= c) == false && (a <=> c) == std::weak_ordering::less && (a <=> c) != std::weak_ordering::equivalent && (a <=> c) != std::weak_ordering::greater && (a <=> c) < 0 && (a <=> c) != 0 && (a <=> c) <= 0 && ""); }
[編輯] 缺陷報告
下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。
| 缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
|---|---|---|---|
| LWG 3431 | C++20 | operator<=> 未要求 T滿足 three_way_comparable |
要求 |