operator==,!=,<,<=,>,>=,<=>(std::set)
来自cppreference.com
在标头 <set> 定义
|
||
(1) | (C++26 起为 constexpr) | |
(2) | (C++20 前) | |
(3) | (C++20 前) | |
(4) | (C++20 前) | |
(5) | (C++20 前) | |
(6) | (C++20 前) | |
(7) | (C++20 起) (C++26 起为 constexpr) |
|
比较两个 set
的内容。
设 value_type
为 set
的值类型(即 typename set::value_type):
1,2) 检查 lhs 与 rhs 的内容是否相等,即它们是否拥有相同数量的元素且 lhs 中每个元素与 rhs 的同位置元素比较相等。
等价于:
return std::distance(lhs.begin(), lhs.end()) |
(C++14 前) |
return std::equal(lhs.begin(), lhs.end(), rhs.begin(), rhs.end()); |
(C++14 起) |
如果
value_type
不可相等比较 (EqualityComparable) ,那么行为未定义。3-7) 按字典序比较 lhs 与 rhs 的内容。
3-6) 等价于 return std::lexicographical_compare(lhs.begin(), lhs.end(),
rhs.begin(), rhs.end());。
rhs.begin(), rhs.end());。
如果满足以下任意条件,那么行为未定义:
-
value_type
不可小于比较 (LessThanComparable) 。 - operator< 未建立全序。
7) 等价于 return std::lexicographical_compare_three_way(lhs.begin(), lhs.end(),
rhs.begin(), rhs.end(),
synth-three-way)。 如果满足以下任意条件,那么行为未定义:
-
T
未实现three_way_comparable
。 - 没有为(可有 const 限定的)
value_type
类型的值定义 operator<。 - operator< 未建立全序。
|
(C++20 起) |
目录 |
[编辑] 参数
lhs, rhs | - | 要比较内容的 set
|
[编辑] 返回值
运算符 | lhs 与 rhs 相等 | lhs 在字典序上更大 | rhs 在字典序上更大 |
---|---|---|---|
operator== | true | false | |
operator!= | false | true | |
operator< | false | false | true |
operator<= | true | ||
operator> | false | true | false |
operator>= | true | ||
operator<=> | 等于 0 的某个值 | 大于 0 的某个值 | 小于 0 的某个值 |
[编辑] 复杂度
1,2) lhs 与 rhs 的大小不同时是常数,否则与
set
的大小成线性。3-7) 与
set
的大小成线性。[编辑] 注解
各关系运算符是基于 |
(C++20 前) |
不定义关系运算符。此时重载决议会选择重写候选 operator<=>。 operator<=> 在有可能时会使用 |
(C++20 起) |
这些非成员比较运算符不会使用 Compare
来比较元素。
[编辑] 示例
运行此代码
#include <cassert> #include <compare> #include <set> int main() { const std::set a{1, 2, 3}, b{1, 2, 3}, c{7, 8, 9, 10}; assert ("" "比较相等的容器:" && (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 && "比较不相等的容器:" && (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
|
需要 |