您的位置:首页 > 产品设计 > UI/UE

priority_queue优先队列的一些用法

2011-03-09 14:25 525 查看
#include <iostream>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;

class Node
{
public:
Node(){first = 0;second = 0;}
Node(int i, int j) : first(i),second(j){}
Node(int i) : first(i){}
int first, second;
};

class cmp
{
public:
bool operator()(const Node &a, const Node &b)
{
if(a.first != b.first)
{
return a.first > b.first;
}
else
{
return a.second > b.second;
}
}
};

int main(void)
{
//cout << "Hello world!" << endl;
int n;
priority_queue<Node, vector<Node>, cmp> que;
while(cin >> n)
{
while(n--)
{
int temp;
cin >> temp;
que.push(Node(temp));
}

while(!que.empty())
{
cout << que.top().first << endl;//读取队首元素
que.pop();//队首元素出队
}
}
return 0;
}


还有:

#include <iostream>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;

struct Node
{
Node(){first = 0;second = 0;}
Node(int i, int j) : first(i),second(j){}
Node(int i) : first(i){}
int first, second;
};

struct cmp
{
bool operator()(const Node &a, const Node &b)
{
if(a.first != b.first)
{
return a.first > b.first;
}
else
{
return a.second > b.second;
}
}
};

int main(void)
{
//cout << "Hello world!" << endl;
int n;
priority_queue<Node, vector<Node>, cmp> que;
while(cin >> n)
{
while(n--)
{
int temp;
cin >> temp;
que.push(Node(temp));
}

while(!que.empty())
{
cout << que.top().first << endl;//读取队首元素
que.pop();//队首元素出队
}
}
return 0;
}


最后一个

#include <iostream>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;

struct cmp
{
bool operator()(const int&a, const int &b)
{
if(a > b)   return true;
else    return false;
}
};//这代表以升序方式

int main(void)
{
//cout << "Hello world!" << endl;
int n;
priority_queue<int, vector<int >, cmp> que;
while(cin >> n)
{
while(n--)
{
int temp;
cin >> temp;
que.push(temp);
}

while(!que.empty())
{
cout << que.top() << endl;//读取队首元素
que.pop();//队首元素出队
}
}
return 0;
}


这几个代码看看应该就会懂。用到了仿函数,以及重载运算符。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: