C++回顾(二十三)—— priority_queue容器

23.1 优先队列概述

  • 最大值优先级队列、最小值优先级队列
  • 优先级队列适配器 STL priority_queue
  • 用来开发一些特殊的应用,请对stl的类库,多做扩展性学习

示例代码:

#include <iostream>
#include <queue>
#include <time.h>
#include <stdlib.h>

using namespace std;

int main()
{
	//priority_queue<int> p;
	//priority_queue<int, vector<int>, less<int> > p;       //等价于priority_queue<int> p;
	
	//priority_queue<int, vector<int>, greater<int> > p;      //less和greater是模板类
	priority_queue<int, deque<int>, greater<int> > p;

	srand(time(NULL));
	int num;
	for (int i = 0; i < 10; i++)
	{
		num = rand() % 20;
		p.push(num);
		cout << num << "进队成功" << endl;
	}

	cout << "队头元素" << p.top() << endl;
	cout << "队列长度" << p.size() << endl;

	while (!p.empty())
	{
		cout << p.top() << "出队" << endl;
		p.pop();
	}

	return 0;
}

运行结果:
在这里插入图片描述

23.2 函数对象functor的用法

  • 尽管函数指针被广泛用于实现函数回调,但C++还提供了一个重要的实现回调函数的方法,那就是函数对象。

  • functor,翻译成函数对象,伪函数,算符,是重载了“()”操作符的普通类对象。从语法上讲,它与普通函数行为类似。greater<>与less<>就是函数对象。

  • 如何实现自定义类型排序
    (1)重载大于或者小于号
    (2)实现仿函数

示例代码:

#include <iostream>
#include <queue>

using namespace std;

class Student
{
	friend class compare;
private:
	int id;
	string name;
public:
	Student(int i, string n);
	void show() const;
	bool operator<(const Student &s) const; 
	bool operator>(const Student &s) const;
};

Student::Student(int i, string n)
{
	id = i;
	name = n;
}

void Student::show() const
{
	cout << "id " << id << "    name " << name << endl;
}

bool Student::operator<(const Student &s) const
{
	return this->id < s.id;
}

bool Student::operator>(const Student &s) const
{
	return this->name > s.name;
}

class compare
{
public:
	bool operator()(const Student &s1, const Student &s2) const
	{
		return s1.id < s2.id;
	}
};

int main()
{
	Student s1(1, "zz");
	Student s2(4, "ff");
	Student s3(3, "bb");
	Student s4(7, "ee");
	Student s5(9, "cc");
	Student s6(5, "dd");

	//priority_queue<Student> p;   //需要Student重载<
	//priority_queue<Student, vector<Student>, less<Student> > p; 
	//priority_queue<Student, vector<Student>, greater<Student> > p;   //需要Student重载>
	priority_queue<Student, vector<Student>, compare> p;

	/*
	compare c;       //函数对象   仿函数   
	c.operator()(s1, s2);
	c(s1, s2);
	*/

	p.push(s1);
	p.push(s2);
	p.push(s3);
	p.push(s4);
	p.push(s5);
	p.push(s6);

	while (!p.empty())
	{
		p.top().show();
		p.pop();
	}

	return 0;
}

运行结果:
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值