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;
}
运行结果: