operator==,!=,<,<=,>,>=,<=>(std::map)
来自 cppreference.cn
定义于头文件 <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++ 标准。
DR | 应用于 | 已发布行为 | 正确行为 |
---|---|---|---|
LWG 3431 | C++20 | operator<=> 不需要 T 建模 three_way_comparable |
需要 |