有关c++ priority_queue的问题
来源:百度知道 编辑:UC知道 时间:2024/06/25 22:56:31
#include <queue>
#include <iostream>
#include "point.h"
using namespace std;
void main()
{
point* a = new point(1,2,3);
point* b = new point(2,3,4);
point* c = new point(3,4,5);
priority_queue<point*> q ;
q.push(b);
q.push(c);
q.push(a);
point* current;
while (!q.empty())
{
current = q.top();
q.pop();
(current->y)--;
if (current->y>0)
{
q.push(current);
}
cout<<current->x<<endl;
}
}
ponit.h如下:
#ifndef _POINT_H_
#define _POINT_H_
using namespace std;
class point
{
public:
int x;
int y;
int z;
point(int a,int b,int c)
{
x = a;
y = b;
z = c;
}
bool operator<(const point& p)
{
return y < p.y;
}
#include <iostream>
#include "point.h"
using namespace std;
void main()
{
point* a = new point(1,2,3);
point* b = new point(2,3,4);
point* c = new point(3,4,5);
priority_queue<point*> q ;
q.push(b);
q.push(c);
q.push(a);
point* current;
while (!q.empty())
{
current = q.top();
q.pop();
(current->y)--;
if (current->y>0)
{
q.push(current);
}
cout<<current->x<<endl;
}
}
ponit.h如下:
#ifndef _POINT_H_
#define _POINT_H_
using namespace std;
class point
{
public:
int x;
int y;
int z;
point(int a,int b,int c)
{
x = a;
y = b;
z = c;
}
bool operator<(const point& p)
{
return y < p.y;
}
利用函数对象,先定义priority_queue的排序规则,
可以继承binary_function并重写operator(),然后如你的程序所写就可以了,
程序如下:
#include <queue>
#include <iostream>
#include "point.h"
#include <functional>
using namespace std;
class PointCmp : public binary_function<point*, point*, bool>
{
public:
bool operator()(point* p1, point* p2) const
{
return p1->y < p2->y;
}
};
void main()
{
point* a = new point(1,2,3);
point* b = new point(2,3,4);
point* c = new point(3,4,5);
priority_queue<point*, deque<point*>, PointCmp> q ;
q.push(b);
q.push(c);
q.push(a);
point* current;
while (!q.empty())
{
current = q.top();
q.pop();
(current->y)--;
if (current->y>0)
{
q.push(current);
}
cout<<current->x&