fork(1) download
  1. #include <iostream>
  2. #include <stack>
  3. #include <queue>
  4. #include <vector>
  5. #include <algorithm>
  6. #include <iterator>
  7. using namespace std;
  8.  
  9. template<class T> void print_queue(T& q) {
  10. while(!q.empty()) {
  11. std::cout << q.top() << " ";
  12. q.pop();
  13. }
  14. std::cout << '\n';
  15. }
  16.  
  17. template<class T>
  18. class priority_stack {
  19. vector<T> stack;
  20. public:
  21. bool empty() const { return stack.size()==0; }
  22. void push(const T& x) {
  23. stack.push_back(x);
  24. for (int i=stack.size()-1; i!=0; i--)
  25. if ( (stack[i]<stack[i-1])) // assuming priority is reflected in order of elements
  26. swap (stack[i-1],stack[i]);
  27. }
  28. void pop() {
  29. if (! empty() )
  30. stack.resize(stack.size()-1);
  31. }
  32. T top() {
  33. if (empty())
  34. throw;
  35. return stack[stack.size()-1];
  36. }
  37. };
  38.  
  39.  
  40. struct data {
  41. int priority;
  42. string message;
  43. bool operator< (const data&a) const {
  44. return priority<a.priority;
  45. }
  46. };
  47.  
  48. ostream& operator<< (ostream& os, const data &x) {
  49. return os<<"("<<x.priority<<","<<x.message<<")";
  50. }
  51.  
  52.  
  53. int main() {
  54. vector<data> d{ { 10, "one"}, {10, "two"}, {11,"high"}, {12,"very high"}, {10,"three"} };
  55. cout << "Data to be pushed:";
  56. copy (d.cbegin(), d.cend(), ostream_iterator<data>(cout," "));
  57. cout<<endl;
  58.  
  59. cout << "Priority queue (FIFO): ";
  60. std::priority_queue<data, std::vector<data>> pq;
  61. for (auto x: d)
  62. pq.push(x);
  63. print_queue(pq);
  64.  
  65. cout << "Priority stack (LIFO): ";
  66. priority_stack<data> ps;
  67. for (auto x: d)
  68. ps.push(x);
  69. print_queue(ps);
  70.  
  71. return 0;
  72. }
Success #stdin #stdout 0s 15248KB
stdin
Standard input is empty
stdout
Data to be pushed:(10,one) (10,two) (11,high) (12,very high) (10,three) 
Priority queue (FIFO): (12,very high) (11,high) (10,one) (10,two) (10,three) 
Priority stack (LIFO): (12,very high) (11,high) (10,three) (10,two) (10,one)