operator==,!=,<,<=,>,>=,<=>(std::list)
來自 cppreference.com
定義於標頭檔案 <list> |
||
(1) | ||
(2) | (C++20 前) | |
(3) | (C++20 前) | |
(4) | (C++20 前) | |
(5) | (C++20 前) | |
(6) | (C++20 前) | |
(7) | (C++20 起) | |
比較兩個 list
的內容。
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)。 如果以下條件均不滿足,則行為未定義
-
T
滿足three_way_comparable
。 - 為型別(可能 const 限定的)
T
的值定義了<
,並且<
是全序關係。
|
(C++20 起) |
目錄 |
[編輯] 引數
lhs, rhs | - | 要比較內容的 list |
-為了使用過載 (1,2),T 必須滿足 EqualityComparable 的要求。 | ||
-為了使用過載 (3-6),T 必須滿足 LessThanComparable 的要求。排序關係必須建立全序。 |
[編輯] 返回值
1) 如果
list
的內容相等,則為 true,否則為 false。2) 如果
list
的內容不相等,則為 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 大小不同,則為常數時間複雜度,否則為
list
大小的線性時間複雜度。3-7)
list
大小的線性時間複雜度。[編輯] 註解
關係運算符是根據元素型別的 operator< 定義的。 |
(C++20 前) |
關係運算符是根據 synth-three-way 定義的,它會盡可能使用 operator<=>,否則使用 operator<。 值得注意的是,如果元素本身不提供 operator<=>,但可以隱式轉換為三向可比較型別,則將使用該轉換而不是 operator<。 |
(C++20 起) |
[編輯] 示例
執行此程式碼
#include <cassert> #include <compare> #include <list> int main() { const std::list a{1, 2, 3}, b{1, 2, 3}, c{7, 8, 9, 10}; 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 |
requires |