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 > constexprstd::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 | - | 要比较的对偶 |
[编辑]返回值
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<,所以存储对偶的容器可以排序。
运行此代码
#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 中的值 (函数模板) |