shushus

Спринт 5. Очередь и дек.

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