1. 程式人生 > 其它 >STL中 greater 和 less

STL中 greater 和 less

技術標籤:C++基礎知識c++

總結

greater 和 less 最好不要記成單獨的升序降序,不然在使用的過程中很容易混亂。單獨記成 左邊 greater 右邊左邊 less 右邊 ,進一步是升序或是降序。在大頂堆小頂堆中,記成最右側為堆頂嗎,上述記憶方法依然適用

正文

greater的原始碼:

		// STRUCT TEMPLATE greater
template<class _Ty = void>
	struct greater
	{	// functor for operator>
	_CXX17_DEPRECATE_ADAPTOR_TYPEDEFS typedef
_Ty first_argument_type; _CXX17_DEPRECATE_ADAPTOR_TYPEDEFS typedef _Ty second_argument_type; _CXX17_DEPRECATE_ADAPTOR_TYPEDEFS typedef bool result_type; constexpr bool operator()(const _Ty& _Left, const _Ty& _Right) const { // apply operator> to operands return (_Left > _Right);
} };

less的原始碼:

		// STRUCT TEMPLATE less
template<class _Ty = void>
	struct less
	{	// functor for operator<
	_CXX17_DEPRECATE_ADAPTOR_TYPEDEFS typedef _Ty first_argument_type;
	_CXX17_DEPRECATE_ADAPTOR_TYPEDEFS typedef _Ty second_argument_type;
	_CXX17_DEPRECATE_ADAPTOR_TYPEDEFS typedef bool
result_type; constexpr bool operator()(const _Ty& _Left, const _Ty& _Right) const { // apply operator< to operands return (_Left < _Right); } };

一般排序中的 greater 和 less

從原始碼中可以看出(return 部分),如果把一個數據序列假想成從左往右依次排列,那麼greater就表示左邊大於右邊,即序列成遞減排列;less表示左邊小於右邊,即序列成遞增排列。
以greater為例,以下兩段程式碼是一致的。

	vector<int> res = { 1,5,7,9,65,785,47,0 };
	sort(res.begin(), res.end(), [](int a, int b) {
		return a < b;
	});
	for (int i = 0; i < res.size(); i++) {
		cout << res[i] << "**";
	}

	vector<int> res = { 1,5,7,9,65,785,47,0 };
	sort(res.begin(), res.end(), less<int>());
	for (int i = 0; i < res.size(); i++) {
		cout << res[i] << "**";
	}

在這裡插入圖片描述

大頂堆、小頂堆中的 greater 和 less

//小頂堆
priority_queue <int,vector<int>,greater<int> > q;
//大頂堆
priority_queue <int,vector<int>,less<int> >q;

以greater為例

	priority_queue <int, vector<int>, greater<int> > q;
	//priority_queue <int, vector<int>, less<int> >q;
	q.push(1); q.push(2); q.push(1); q.push(5); q.push(3);
	while (!q.empty()) {
		cout << q.top() << "**";
		q.pop();
	}

在這裡插入圖片描述
頂部始終是最小值。