与有序表、哈希表一样,队列实现的大小根堆也是分两种:内建数据和自定义对象数据。
1.内建数据大根堆
2.内建数据小根堆 greater<int>
3. 自定义对象大根堆
4.自定义对象小根堆 重载<
基本就是 :
priority_queue<int> xxx 大根堆
priority_queue<int, vector<int>, greater<int>> xxxx 小根堆
1.内建数据大根堆
void priority_maxQueue_int()
{
cout<<"**priority_maxQueue_int**********"<<endl;
priority_queue<int> qmax;
int a[5] = { 3,5,9,6,2 };
int m_len = 5;
for (int i = 0; i < m_len; i++)
{
qmax.push(a[i]);
}
for (int i = 0; i < m_len; i++)
{
cout << qmax.top() << " ";
qmax.pop();
}
//9 6 5 3 2
}
2.内建数据小根堆 greater<int>
void priority_minQueue_int()
{
cout << "*priority_minQueue_int*******" << endl;
//priority_queue<Type, Container, Functional>
//Type 为数据类型, Container 为保存数据的容器,Functional 为元素比较方式。
priority_queue<int, vector<int>, greater<int>> qmin;
int a[5] = { 3,5,9,6,2 };
int m_len = 5;
for (int i = 0; i < m_len; i++)
{
qmin.push(a[i]);
}
for (int i = 0; i < m_len; i++)
{
cout << qmin.top() << " ";//弹出
qmin.pop(); //删除
}
//2 3 5 6 9
}
3.自定义对象
class Node_priority
{
public:
int x;
int y;
Node_priority(int a, int b)
{
x = a;
y = b;
}
bool operator < (const Node_priority& n) const
{
if (n.x==x)
{
return y > n.y;
}
return x > n.x;
}
};
4. 自定义对象大根堆
void priority_maxQueue_node()
{
cout << "**priority_maxQueue_node**********" << endl;
priority_queue<Node_priority> qmax;
for (int i = 0; i < 10; i++)
{
qmax.push(Node_priority(rand(), rand()));
}
while (!qmax.empty())
{
cout << qmax.top().x << ' ' << qmax.top().y << endl;
qmax.pop();
}
}
5.自定义对象小根堆 重载<
cout << "**priority_minQueue_node**********" << endl;
priority_queue<Node_priority, vector<Node_priority>> qmin;
for (int i = 0; i < 10; ++i)
{
qmin.push(Node_priority(rand(), rand()));
}
while (!qmin.empty())
{
cout << qmin.top().x << ' ' << qmin.top().y << endl;
qmin.pop();
}