Advertisement
35657

Untitled

Jun 29th, 2024
426
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.05 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5.  
  6. template<typename T>
  7. class Array {
  8.  
  9. public:
  10.  
  11.     int get_size() const {
  12.         return size;
  13.     }
  14.  
  15.     T get_item(size_t index) const {
  16.         if (index >= 0 && index < size) {
  17.             return arr[index];
  18.         }
  19.     }
  20.  
  21.     void set_item(size_t index, T value) {
  22.         if (index >= 0 && index < size) {
  23.             arr[index] = value;
  24.         }
  25.     }
  26.  
  27.     void print() {
  28.         for (int i = 0; i < size; i++) {
  29.             cout << arr[i] << " ";
  30.         }
  31.         cout << endl;
  32.     }
  33.  
  34.     void sort() {
  35.         for (int k = 0; k < size; k++) {
  36.             for (int j = 0; j < size - 1; j++) {
  37.                 if (arr[j] > arr[j + 1]) {
  38.                     T temp = arr[j];
  39.                     arr[j] = arr[j + 1];
  40.                     arr[j + 1] = temp;
  41.                 }
  42.             }
  43.         }
  44.     }
  45.  
  46. private:
  47.     static const size_t size = 5;
  48.     T arr[size]{}; // без фигурных скобок массив не будет инициализирован значениями по умолчанию
  49. };
  50.  
  51. int main() {
  52.  
  53.     cout << "Class Tempate Array" << endl << endl;
  54.  
  55.     Array<int> int_array;
  56.     cout << "int Array initialization:" << endl;
  57.     int_array.print();
  58.     int size = int_array.get_size();
  59.     for (int i = 0; i < size; i++) {
  60.         int_array.set_item(i, rand() % 10);
  61.     }
  62.     cout << endl << "int Array after assignment:" << endl;
  63.     int_array.print();
  64.     int_array.sort();
  65.     cout << endl << "int Array after ordering:" << endl;
  66.     int_array.print();
  67.     cout << endl;
  68.  
  69.     Array<string> str_array;
  70.     cout << "str Array initialization:" << endl;
  71.     str_array.print();
  72.     str_array.set_item(0, "two");
  73.     str_array.set_item(1, "seven");
  74.     str_array.set_item(2, "zero");
  75.     str_array.set_item(3, "four");
  76.     str_array.set_item(4, "one");
  77.     cout << endl << "str Array after assignment:" << endl;
  78.     str_array.print();
  79.     str_array.sort();
  80.     cout << endl << "str Array after ordering:" << endl;
  81.     str_array.print();
  82. }
  83.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement