operator==,!=,<,<=,>,>=,<=>(std::pair)
来自 cppreference.cn
在头文件 <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 > constexpr std::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 | - | 要比较的 pair |
[编辑] 返回值
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< 为 pair 定义,因此 pair 的容器可以排序。
运行此代码
#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 中的值 (函数模板) |