C++/Data Structure/Priority Queue
Содержание
Demonstrate a priority_queue.
#include <iostream>
#include <queue>
using namespace std;
int main()
{
priority_queue<int> queueObject;
queueObject.push(1);
queueObject.push(3);
queueObject.push(4);
while(!queueObject.empty()) {
cout << "Popping ";
cout << queueObject.top() << endl;
queueObject.pop();
}
return 0;
}
PriorityQueue: push, pop and top
#include <iostream>
#include <string>
#include <queue>
using namespace std;
class Prioritize {
public:
int operator() ( const pair<string, unsigned int>& p1,
const pair<string, unsigned int>& p2 ) {
return p1.second < p2.second;
}
};
int main()
{
priority_queue< pair< string, unsigned int >,
vector <pair< string, unsigned int > >, Prioritize > pq;
pq.push( pair<string, int>( "Event 1", 2) );
pq.push( pair<string, int>( "Event 2", 10 ) );
pq.push( pair<string, int>( "Event 3", 1 ) );
while ( !pq. empty() ) {
cout << pq.top().first << endl;
pq.pop();
}
return 0;
}
Storing class objects in a priority_queue.
#include <iostream>
#include <queue>
#include <string>
using namespace std;
class Thread {
int priority;
string name;
public:
Thread() {
name = "";
priority = 0;
}
Thread(string n, int p) {
name = n;
priority = p;
}
string getname() const {
return name;
}
int getpriority() const {
return priority;
}
};
// Determine priority.
bool operator<(const Thread &a, const Thread &b)
{
return a.getpriority() < b.getpriority();
}
int main()
{
priority_queue<Thread> q;
q.push(Thread("F", 10));
q.push(Thread("M", 2));
// show priority
cout << "Priorities: ";
while(!q.empty()) {
cout << q.top().getname() << endl;
cout << " ";
q.pop();
}
return 0;
}
Using a different comparison function: greater
#include <iostream>
#include <queue>
#include <functional>
using namespace std;
int main()
{
priority_queue<int, vector<int>, greater<int> > q;
q.push(1);
q.push(3);
q.push(4);
while(!q.empty()) {
cout << "Popping ";
cout << q.top() << endl;
q.pop();
}
return 0;
}