Dec 19, 2010

STL queue 优先队列

创建自定义类型,存入优先队列
#include <list>
#include <queue>
#include <string>
#include <iostream>
#include <algorithm>

using namespace std;

class T
{
public:
 T(int arg1,int arg2, string arg3):a(arg1),b(arg2),name(arg3) {}
 int geta() const { return a; }
 int getb() const { return b; }
 const string& getname() const { return name; }

 friend bool operator<(const T&t1, const T&t2);
 friend ostream& operator<<(ostream& os, const T& t);

private:
 int a;
 int b;
 string name;
};

ostream& operator<<(ostream& os, const T& t)
{
 os << t.getname() << ' ' << t.geta() + t.getb();
 return os;
}

bool operator<(const T& t1, const T& t2)
{
 return (t1.geta()+t1.getb())<(t2.geta()+t2.getb());
}

int main()
{
 priority_queue<T> q;
 q.push(T(1,0,"t1"));
 q.push(T(4,2,"t2"));
 q.push(T(0,1,"t3"));
 q.push(T(4,1,"t4"));

 cout << q.top() << endl;
 q.pop();
 cout << q.top() << endl;
 q.pop();
 cout << q.top() << endl;
 q.pop();
 cout << q.top() << endl;
 q.pop();
 return 0;
}

0 comments: