How to print out a priority queue?
Feb 19, 2017 at 12:18pm UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
#include "stdafx.h"
#include <queue>
#include <iostream>
#include <functional>
#include <vector>
using namespace std;
struct CustomCompare
{
bool operator ()(const int & lhs, const int & rhs)
{
return lhs < rhs;
}
};
int main()
{
priority_queue<int , vector<int >, CustomCompare > pq;
pq.push(3);
pq.push(5);
pq.push(1);
pq.push(8);
//want to print out the priority queue using CustomCompare to adjust ordering
return 0;
}
Last edited on Feb 19, 2017 at 12:24pm UTC
Feb 19, 2017 at 12:30pm UTC
I think I may have answered my own question? This seems from my point of view to work correctly but was wondering if someone with more experience of using priority queues or c++ could verify that?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
#include "stdafx.h"
#include <queue>
#include <iostream>
#include <functional>
#include <vector>
using namespace std;
struct CustomCompare
{
bool operator ()(const int & lhs, const int & rhs)
{
return lhs < rhs;
}
};
template <typename A> void print_queue(A& pq)
{
while (!pq.empty())
{
cout << pq.top() << endl;
pq.pop();
}
}
int main()
{
priority_queue<int , vector<int >, CustomCompare > pq;
//inserts initial elements to queue
pq.push(3);
pq.push(5);
pq.push(1);
pq.push(8);
print_queue(pq);
//inserts 55 into queue
pq.push(55);
//print_queue(pq);
//deletes element from queue
pq.pop();
print_queue(pq);
}
Topic archived. No new replies allowed.