C++ Priority Queues(优先队列)
cpp
#include <iostream>
#include <string.h>
#include <queue>
using namespace std;
class people
{
private:
string name;
int age;
public:
people(string name, int age)
{
this->name = name;
this->age = age;
}
string &getname()
{
return name;
}
int &getage()
{
return age;
}
};
ostream &operator<<(ostream &out, people d) // 重载<< cout只能传引用
{
out << d.getname() << " " << d.getage();
return out;
}
class agocmp//定义优先规则
{
public:
bool operator()(people &p1, people &p2)
{
return p1.getage() > p2.getage();
}
};
int main(int argc, char const *argv[])
{
priority_queue<people, vector<people>, agocmp> q;
people P1("张山", 15);
people P2("李四", 10);
people P3("王五", 30);
people P4("赵六", 40);
q.push(P1);
q.push(P2);
q.push(P3);
q.push(P4);
while (!q.empty()){
cout << q.top() << endl;
q.pop();
}
return 0;
}
注意:优先规则需要自己定义一个类,然后在类里重载一下运算符(),好像还有另外一种方式具体我不记得了,好像是重载一下>还是<具体不记得。
empty
语法:
|-----------------------|
| bool empty();
|
empty()函数返回真(true)如果优先队列为空,否则返回假(false)。
pop
语法:
|---------------------|
| void pop();
|
pop()函数删除优先队列中的第一个元素。
push
语法:
|---------------------------------------|
| void push( const TYPE &val );
|
push()函数添加一个元素到优先队列中,值为val。
size
语法:
|---------------------------|
| size_type size();
|
size()函数返回优先队列中存储的元素个数。
top
语法:
|----------------------|
| TYPE &top();
|
top()返回一个引用,指向优先队列中有最高优先级的元素。注意只有pop()函数删除一个元素。