UNBZN
Jun 4th, 2024
129
0
Never
This is comment for paste Untitled
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Hello look this its better :
  2. #include <iostream>
  3. #include <fstream>
  4. #include <vector>
  5. #include <string>
  6.  
  7. class Queue {
  8. public:
  9. explicit Queue(int max_size) : size_(0), max_size_(max_size), head_(0), tail_(0), queue_(max_size) {}
  10.  
  11. bool push(int x) {
  12. if (size_ >= max_size_) {
  13. std::cout << "Queue is full" << std::endl;
  14. return false;
  15. }
  16. queue_[tail_] = x;
  17. tail_ = (tail_ + 1) % max_size_;
  18. ++size_;
  19. return true;
  20. }
  21.  
  22. bool pop() {
  23. if (empty()) {
  24. std::cout << "Queue is empty" << std::endl;
  25. return false;
  26. }
  27. std::cout << queue_[head_] << std::endl;
  28. head_ = (head_ + 1) % max_size_;
  29. --size_;
  30. return true;
  31. }
  32.  
  33. void peek() const {
  34. if (empty()) {
  35. std::cout << "Queue is empty" << std::endl;
  36. } else {
  37. std::cout << queue_[head_] << std::endl;
  38. }
  39. }
  40.  
  41. void display_size() const {
  42. std::cout << size_ << std::endl;
  43. }
  44.  
  45. bool empty() const {
  46. return size_ == 0;
  47. }
  48.  
  49. private:
  50. std::vector<int> queue_;
  51. int size_;
  52. int max_size_;
  53. int head_;
  54. int tail_;
  55. };
  56.  
  57. int main() {
  58. std::ifstream fin("input.txt");
  59. if (!fin) {
  60. std::cerr << "Error opening file" << std::endl;
  61. return 1;
  62. }
  63.  
  64. int count, size;
  65. fin >> count >> size;
  66. Queue queue(size);
  67.  
  68. std::string command;
  69. int num;
  70.  
  71. while (count-- > 0 && fin >> command) {
  72. if (command == "push") {
  73. fin >> num;
  74. queue.push(num);
  75. } else if (command == "pop") {
  76. queue.pop();
  77. } else if (command == "peek") {
  78. queue.peek();
  79. } else if (command == "size") {
  80. queue.display_size();
  81. }
  82. }
  83.  
  84. return 0;
  85. }
  86.  
  87. • BETTER POINT :
  88.  
  89. • Renamed the size() method to display_size() to avoid confusion with the size_ class member.
  90. • Added checks to ensure the “input.txt” file opens correctly.
  91. • Simplified the command reading loop using a while loop.
  92. • Introduced the empty() method to check if the queue is empty before performing pop or peek.
  93. • Provided more descriptive error messages for when the queue is full or empty.
  94. • Made the peek() method const, as it does not modify the state of the object.
  95. • Added boolean returns for the push and pop methods to indicate the success or failure of the operation.
Advertisement
Add Comment
Please, Sign In to add comment