Advertisement
35657

Untitled

May 17th, 2024
391
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 6.37 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. template <typename T>
  6. class Vector {
  7.  
  8. public:
  9.     Vector() : size_(0), capacity_(4), arr_(new T[4]) {}
  10.  
  11.     explicit Vector(const int vector_capacity) : size_(0), capacity_(vector_capacity), arr_(new T[vector_capacity]) {}
  12.  
  13.     Vector(const Vector& other) : size_(other.size_), capacity_(other.capacity_), arr_(new T[capacity_]) {
  14.         for (int i = 0; i < size_; i++) {
  15.             arr_[i] = other.arr_[i];
  16.         }
  17.         total_number_elements_ += size_;
  18.     } // конструктор копирования
  19.  
  20.     Vector(const initializer_list<T>& list) : size_(list.size()), capacity_(list.size()), arr_(new T[list.size()]) {
  21.         int i = 0;
  22.         for (const T& element : list) {
  23.             arr_[i] = element;
  24.             i++;
  25.         }
  26.     }
  27.  
  28.     Vector& operator=(const Vector& other) {
  29.         if (&other != this) { // проверка на самоприсваивание
  30.             total_number_elements_ += other.size_ - size_; // общее количество увеличивается (уменьшается) на разность элементов
  31.             size_ = other.size_;
  32.             capacity_ = other.capacity_;
  33.             delete[] arr_;
  34.             arr_ = new T[capacity_];
  35.             for (int i = 0; i < size_; i++) {
  36.                 arr_[i] = other.arr_[i];
  37.             }
  38.         }
  39.         return *this;
  40.     } // копирующий оператор присваивания =
  41.  
  42.     Vector(Vector&& other) : size_(other.size_), capacity_(other.capacity_), arr_(other.arr_) {
  43.         other.arr_ = nullptr;
  44.         other.size_ = 0;
  45.         other.capacity_ = 0;
  46.     } // конструктор перемещения
  47.  
  48.     Vector& operator=(Vector&& other) {
  49.         if (&other != this) {
  50.             total_number_elements_ += other.size_ - size_; // общее количество увеличивается (уменьшается) на разность элементов
  51.             size_ = other.size_;
  52.             capacity_ = other.capacity_;
  53.             delete[] arr_;
  54.             arr_ = other.arr_;
  55.             other.arr_ = nullptr;
  56.             other.size_ = 0;
  57.             other.capacity_ = 0;
  58.         }
  59.         return *this;
  60.     } // перемещающий оператор присваивания =
  61.  
  62.     void push_back(const T& value) {
  63.         check_capacity();
  64.         arr_[size_] = value;
  65.         size_++;
  66.         total_number_elements_++;
  67.     }
  68.  
  69.     void pop_back() {
  70.         if (size_ > 0) {
  71.             size_--;
  72.         }
  73.         total_number_elements_--;
  74.     }
  75.  
  76.     void insert(const int index, const T& value) { // типы ошибок можно разделить
  77.         if (index < 0) {
  78.             throw invalid_argument("Индекс не может быть меньше нуля");
  79.         }
  80.         if (index >= size_) {
  81.             throw out_of_range("Индекс превышает размер вектора");
  82.         }
  83.         check_capacity();
  84.         for (int i = size_; i > index; i--) {
  85.             arr_[i] = arr_[i - 1];
  86.         }
  87.         arr_[index] = value;
  88.         size_++;
  89.         total_number_elements_++;
  90.     }
  91.  
  92.     void erase(const int index) {
  93.         if (index < 0 || index >= size_) {
  94.             cout << "Некорректный индекс" << endl;
  95.             return;
  96.         }
  97.         for (int i = index; i < size_ - 1; i++) {
  98.             arr_[i] = arr_[i + 1];
  99.         }
  100.         size_--;
  101.         total_number_elements_--;
  102.     }
  103.  
  104.     T& operator[](const int index) {
  105.         if (index < 0 || index >= size_) {
  106.             cout << "Некорректный индекс" << endl;
  107.         }
  108.         return arr_[index];
  109.     }
  110.  
  111.     const T& operator[](const int index) const {
  112.         if (index < 0 || index >= size_) {
  113.             cout << "Некорректный индекс" << endl;
  114.         }
  115.         return arr_[index];
  116.     }
  117.  
  118.     int size() const {
  119.         return size_;
  120.     }
  121.  
  122.     int capacity() const {
  123.         return capacity_;
  124.     }
  125.  
  126.     bool operator==(const Vector& right) const {
  127.         if (right.size_ != size_) {
  128.             return false;
  129.         }
  130.         for (int i = 0; i < size_; i++) {
  131.             if (arr_[i] != right.arr_[i])
  132.                 return false;
  133.         }
  134.         return true;
  135.     }
  136.  
  137.     bool operator!=(const Vector& right) const {
  138.         return !(*this == right);
  139.     }
  140.  
  141.     void print() const {
  142.         for (int i = 0; i < size_; i++) {
  143.             cout << arr_[i] << " ";
  144.         }
  145.         cout << endl;
  146.     }
  147.  
  148.     static int get_total_number_elements() {
  149.         return total_number_elements_;
  150.     }
  151.  
  152.  
  153.     ~Vector() {
  154.         delete[] arr_;
  155.         total_number_elements_ -= size_;
  156.     }
  157.  
  158. private:
  159.  
  160.     void check_capacity() {
  161.         if (size_ == capacity_) {
  162.             int* temp = new int[capacity_ * 2];
  163.             for (int i = 0; i < size_; i++) {
  164.                 temp[i] = arr_[i];
  165.             }
  166.             delete[] arr_;
  167.             arr_ = temp;
  168.             capacity_ *= 2;
  169.         }
  170.     }
  171.  
  172.     int size_; // текущее количество элементов
  173.     int capacity_; // емкость хранилища
  174.     T* arr_; // хранилище
  175.     static int total_number_elements_; // общее количество элементов по всем векторам
  176. };
  177.  
  178. template <typename T>
  179. int Vector<T>::total_number_elements_ = 0;
  180.  
  181.  
  182. int main() {
  183.     setlocale(LC_ALL, "ru");
  184.  
  185.     Vector<int> vec{ 1,2,3,4,5 };
  186.  
  187.     vec.print();
  188.  
  189.     //vec.insert(9, 12); // в блок try оборачиваем функцию (блок кода) где может быть выброшено исключение
  190.  
  191.     try {
  192.         vec.insert(9, 12); // в блок try оборачиваем функцию (блок кода) где может быть выброшено исключение
  193.     }
  194.  
  195.     catch (const out_of_range& ex) { // ловим в одном блоке catch конкретный тип ошибки
  196.         cout << ex.what() << endl;
  197.     }
  198.     catch(const logic_error& ex) { // ловим в одном блоке catch любые ошибки разновидности logic_error
  199.         cout << ex.what() << endl;
  200.     }
  201.     catch (...) { // ловим ошибки любого другого типа
  202.         cout << "Другая ошибка" << endl;
  203.     }
  204.    
  205.  
  206.     vec.print();
  207.  
  208. }
  209.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement