Advertisement
chevengur

СПРИНТ № 5 | Стек, очередь, дек | Урок 3: Очередь и дек

Feb 20th, 2024
900
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.44 KB | None | 0 0
  1. #include <stack>
  2. #include <iostream>
  3. #include <algorithm>
  4. #include <vector>
  5. #include <random>
  6. #include <numeric>
  7.  
  8. using namespace std;
  9.  
  10. template <typename It>
  11. void PrintRange(It range_begin, It range_end) {
  12.     for (auto it = range_begin; it != range_end; ++it) {
  13.         cout << *it << " "s;
  14.     }
  15.     cout << endl;
  16. }
  17.  
  18. template <typename Type>
  19. class Queue {
  20. public:
  21.     void Push(const Type& element) {
  22.         stack1_.push(element);
  23.     }
  24.     void Pop() {
  25.         MoveElem();
  26.         stack2_.pop();
  27.     }
  28.     Type& Front() {
  29.         MoveElem();
  30.         return stack2_.top();
  31.     }
  32.     uint64_t Size() const {
  33.         return stack1_.size() + stack2_.size();
  34.     }
  35.     bool IsEmpty() const {
  36.         return (stack1_.empty() && stack2_.empty());
  37.     }
  38.  
  39. private:
  40.     stack<Type> stack1_;
  41.     stack<Type> stack2_;
  42.  
  43.     void MoveElem() {
  44.         if (stack2_.empty()) {
  45.             while (!stack1_.empty()) {
  46.                 stack2_.push(stack1_.top());
  47.                 stack1_.pop();
  48.             }
  49.         }
  50.     }
  51. };
  52.  
  53. int main() {
  54.     setlocale(0, "");
  55.     Queue<int> queue;
  56.     vector<int> values(5);
  57.     // заполняем вектор для тестирования очереди
  58.     iota(values.begin(), values.end(), 1);
  59.     // перемешиваем значения
  60.     random_device rd;
  61.     mt19937 g(rd());
  62.     shuffle(values.begin(), values.end(), g);
  63.     PrintRange(values.begin(), values.end());
  64.     cout << "Заполняем очередь"s << endl;
  65.     // заполняем очередь и выводим элемент в начале очереди
  66.     for (int i = 0; i < 5; ++i) {
  67.         queue.Push(values[i]);
  68.         cout << "Вставленный элемент "s << values[i] << endl;
  69.         cout << "Первый элемент очереди "s << queue.Front() << endl;
  70.     }
  71.     cout << "Вынимаем элементы из очереди"s << endl;
  72.     // выводим элемент в начале очереди и вытаскиваем элементы по одному
  73.     while (!queue.IsEmpty()) {
  74.         // сначала будем проверять начальный элемент, а потом вытаскивать,
  75.         // так как операция Front на пустой очереди не определена
  76.         cout << "Будем вынимать элемент "s << queue.Front() << endl;
  77.         queue.Pop();
  78.     }
  79.     return 0;
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement