35657

Untitled

Sep 7th, 2024
176
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.63 KB | None | 0 0
  1.  
  2. #include <iostream>
  3. #include <typeinfo>
  4.  
  5. using namespace std;
  6.  
  7. template <typename T>
  8. class Vector {
  9. public:
  10.  
  11.     Vector() : size(0), capacity(4), arr(new T[4]) {}
  12.  
  13.     void Push_back(const T value) {
  14.         if (size == capacity) {
  15.             T* temp = new T[capacity * 2];
  16.             for (int i = 0; i < size; i++) {
  17.                 temp[i] = arr[i];
  18.             }
  19.             delete[] arr;
  20.             arr = temp;
  21.             capacity *= 2;
  22.         }
  23.         arr[size] = value;
  24.         size++;
  25.     }
  26.  
  27.     void Insert(const int index, const T value) {
  28.         if (index < 0) { // намеренно разделили две ошибки
  29.             throw invalid_argument("Индекс не может быть меньше нуля");
  30.         }
  31.         if (index >= size) {
  32.             throw out_of_range("Индекс превышает размер вектора");
  33.         }
  34.         if (size == capacity) {
  35.             T* temp = new T[capacity * 2];
  36.             for (int i = 0; i < size; i++) {
  37.                 temp[i] = arr[i];
  38.             }
  39.             delete[] arr;
  40.             arr = temp;
  41.             capacity *= 2;
  42.         }
  43.         for (int i = size; i > index; i--) {
  44.             arr[i] = arr[i - 1];
  45.         }
  46.         arr[index] = value;
  47.         size++;
  48.     }
  49.  
  50.     void Print() {
  51.         for (int i = 0; i < size; i++) {
  52.             cout << arr[i] << " ";
  53.         }
  54.         cout << endl;
  55.     }
  56.  
  57.     ~Vector() {
  58.         delete[] arr;
  59.     }
  60.  
  61. private:
  62.     int size;
  63.     int capacity;
  64.     T* arr;
  65. };
  66.  
  67. int main() {
  68.  
  69.     setlocale(LC_ALL, "ru");
  70.  
  71.     Vector<int> vec;
  72.  
  73.     for (int i = 0; i < 5; i++) {
  74.         vec.Push_back(i + 1);
  75.     }
  76.  
  77.     vec.Print();
  78.  
  79.  
  80.     try {
  81.         vec.Insert(8, 10);
  82.     }
  83.     catch (const out_of_range& ex) { // здесь ловим out_of_range
  84.         cout << ex.what() << endl;
  85.     }
  86.     catch (const invalid_argument& ex) { // а здесь invalid_argument
  87.         cout << ex.what() << endl;
  88.     }
  89. }
Advertisement
Add Comment
Please, Sign In to add comment