关于std::pair的比较运算

1 关于pair的比较运算

在8.2.1(P291)中,有一段muduo源码:

typedef std::pair<TimeStamp, Timer*> Entry;
typedef std::set<Entry> TimerList;

比较疑惑为什么没有给set提供比较函数,后来才想起来pair有实现operator<:
(摘抄自".\VisualStudio\2017\Enterprise\VC\Tools\MSVC\14.12.25827\include\utility")

template<class _Ty1,
	class _Ty2>
	constexpr bool operator<(const pair<_Ty1, _Ty2>& _Left,
		const pair<_Ty1, _Ty2>& _Right)
	{	// test if _Left < _Right for pairs
	return (_Left.first < _Right.first ||
		(!(_Right.first < _Left.first) && _Left.second < _Right.second));
	}

2 关联容器是如何判定两个元素相等的

当关联容器(std::map/std::set)中存放自定义类型时,并没有重载operator==,那么它是如何判定两个元素相等的呢?
cppreference上的解释是"In imprecise terms, two objects a and b are considered equivalent if neither compares less than the other: !comp(a, b) && !comp(b, a)."。
这就解释了为什么我们只重载自定义类型的operator<,就实现了排序加判等。
关联容器的find/count/lower_bound/upper_bound方法都会用到判等。
用了好久关联容器,最近才想明白这个道理,记录一下。

猜你喜欢

转载自www.cnblogs.com/bwzdxl/p/13385904.html