operator==,!=,<,<=,>,>=,<=>(std::pair)_C++中文网
template< class T1, class T2 >
bool operator!=( const std::pair<T1,T2>& lhs, const std::pair<T1,T2>& rhs );
template< class T1, class T2 >
constexpr bool operator!=( const std::pair<T1,T2>& lhs,
(C++20 前) (3)
template< class T1, class T2 >
bool operator<( const std::pair<T1,T2>& lhs, const std::pair<T1,T2>& rhs );
template< class T1, class T2 >
constexpr bool operator<( const std::pair<T1,T2>& lhs,
(C++20 前) (4)
template< class T1, class T2 >
bool operator<=( const std::pair<T1,T2>& lhs, const std::pair<T1,T2>& rhs );
template< class T1, class T2 >
constexpr bool operator<=( const std::pair<T1,T2>& lhs,
(C++20 前) (5)
template< class T1, class T2 >
bool operator>( const std::pair<T1,T2>& lhs, const std::pair<T1,T2>& rhs );
template< class T1, class T2 >
constexpr bool operator>( const std::pair<T1,T2>& lhs,
(C++20 前) (6)
template< class T1, class T2 >
bool operator>=( const std::pair<T1,T2>& lhs, const std::pair<T1,T2>& rhs );
template< class T1, class T2 >
constexpr bool operator>=( const std::pair<T1,T2>& lhs,
(C++20 前)
template< class T1, class T2 >
constexpr /* see below */ operator<=>( const std::pair<T1,T2>& lhs,
1-2) 测试 lhs 和 rhs 的两个元素是否均相等,即比较 lhs.first 和 rhs.first 及 lhs.second 和 rhs.second
3-6) 用 operator< 按字典序比较 lhs 和 rhs ,即比较首元素,然后仅若它们等价,再比较第二元素。
7) 用合成三路比较按字典序比较 lhs 和 rhs ,即比较首元素,然后仅若它们等价,再比较第二元素。
返回类型为 T1 与 T2 上的合成三路比较类型的结果类型的共用比较类别类型。
合成三路比较给定对象类型
lhs < rhs ? std::weak_ordering::less : rhs < lhs ? std::weak_ordering::greater : std::weak_ordering::equivalent
若 three_way_comparable_with 或 |
(C++20 起) |
参数
返回值
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) ,其中 synth_three_way 是仅用于阐释的进行合成三路比较的函数对象。
示例
因为 operator< 为 pair 定义,故 pair 的容器能排序。
#include <iostream> #include <utility> #include <vector> #include <algorithm> #include <string> 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 << "," << p.second << ")\n"; } }
输出: