STL的greater与less

greater<T>()和less<T>()分别是用于升序和降序排列时用的。头文件是<functional>

一、sort的greater与less

sort默认是less 是生成一个从小到大的排序。  使用greater是一个从大到小的排序。

#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;

template <class T>
void printT(T t)
{
	for (T::iterator it = t.begin(); it != t.end(); it++)
	{
		cout << *it << " ";
	}
	cout << endl;
}



int main()
{
	vector<int> num;
	num.push_back(3);
	num.push_back(2);
	num.push_back(8);
	num.push_back(5);
	num.push_back(9);
	num.push_back(4);


	sort(num.begin(), num.end());                 //默认是从小到大 less
	printT<vector<int>>(num);

	sort(num.begin(), num.end(),greater<int>());  //默认是从大到小 greater
	printT<vector<int>>(num);

	system("pause");
	return 0;
}

输出是

二、make_heap push_heap  pop_heap里的less与greater

make_heap里的less是生成一个从大到小的最大堆。greater是生成一个从小到大的最小堆。puh_heap和pop_heap同理。

#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;

template <class T>
void printT(T t)
{
	for (T::iterator it = t.begin(); it != t.end(); it++)
	{
		cout << *it << " ";
	}
	cout << endl;
}



int main()
{
	vector<int> num;
	num.push_back(3);
	num.push_back(2);
	num.push_back(8);
	num.push_back(5);
	num.push_back(9);
	num.push_back(4);


	make_heap(num.begin(), num.end());   //可以这样理解,逐渐减小。默认是从大到小 less   最大堆:首元素是对最大的
	printT<vector<int>>(num);

	//push_heap与push_back结合使用,push_back先将元素压入尾部,push_heap在将刚放入尾部的最后一个元素插入到合适的位置。O(logn)
	//注意的是push_heap必须跟make_heap的less 或greater保持一致
	num.push_back(10);
	push_heap(num.begin(), num.end());  
	printT<vector<int>>(num);


	//pop_heap与pop_back结合使用,pop_heap先将头部元素移到尾部,然后pop_back在将元素弹出。O(logn)
	//注意的是pop_heap必须跟make_heap的less 或greater保持一致
	pop_heap(num.begin(), num.end());
	num.pop_back();
	printT<vector<int>>(num);


	system("pause");
	return 0;
}

输出是

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值