Advertisement
dimon-torchila

Untitled

Dec 15th, 2022
841
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.91 KB | None | 0 0
  1. #include "bits/stdc++.h"
  2.  
  3. using namespace std;
  4.  
  5. namespace lab1{
  6.     class Queue{
  7.     public:
  8.         Queue(int size) : length(size), arr(new int[size]), begin(0), count(0), end(-1){ }
  9.         ~Queue(){ delete []arr;}
  10.         void push(int el){
  11.             if(isFull())
  12.                 resize(length + length / 10);
  13.             ++end%=length;
  14.             arr[end] = el;
  15.             count++;
  16.         }
  17.         void pop(){
  18.             if(!isEmpty()){
  19.                 arr[begin] = INT_MIN;
  20.                 ++begin%=length;
  21.                 count--;
  22.             } else {
  23.                 throw runtime_error("going beyond the boundaries of the array");
  24.             }
  25.         }
  26.         int front(){
  27.             return arr[begin];
  28.         }
  29.         void resize(int new_size){
  30.             int *arr2 = arr;
  31.             arr = new int[new_size];
  32.             for(int i = 0; i < length; ++i){
  33.                 arr[i] = arr2[(i + begin) % length];
  34.             }
  35.             begin = 0;
  36.             end = length - 1;
  37.             length = new_size;
  38.         }
  39.         bool isEmpty(){ return size() == 0; }
  40.         bool isFull() { return size() == count; }
  41.         int size() { return length; }
  42.  
  43.         void sort(){
  44.             for(int i = begin; i < begin + count - 1; ++i){
  45.                 int min = i%length;
  46.                 for(int j = i + 1; j < begin + count; ++j){
  47.                     if(arr[j%length] < arr[min])
  48.                         min = j%length;
  49.                 }
  50.                 swap(arr[i%length], arr[min]);
  51.             }
  52.         }
  53.  
  54.         void print(){
  55.             for(int i = begin; i < begin + count; ++i)
  56.                 cout << arr[i%length] << ' ';
  57.             cout << endl;
  58.         }
  59.  
  60.     private:
  61.         int *arr;
  62.         int length;
  63.         int begin;
  64.         int end;
  65.         int count;
  66.     };
  67. }
  68.  
  69. #ifndef UNTITLED1_LAB1_H
  70. #define UNTITLED1_LAB1_H
  71.  
  72. #endif //UNTITLED1_LAB1_H
Advertisement
Comments
  • CyberN00b
    2 years
    # text 0.47 KB | 0 0
    1. 12 строка: если length < 10, то размер изменяться не будет. Так же при малом length, ресайз будет неэффективным и 10 <= length < 20, push будет работать всегда за O(n). Замени на length * 2;
    2. 26 строка: если очередь пуста, то throw;
    3. 35 строка: утечка памяти, забываешь удалять исходный массив. delete []arr2;
Add Comment
Please, Sign In to add comment
Advertisement