Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- template<typename T>
- class Array {
- public:
- int get_size() const {
- return size;
- }
- T get_item(size_t index) const {
- if (index >= 0 && index < size) {
- return arr[index];
- }
- }
- void set_item(size_t index, T value) {
- if (index >= 0 && index < size) {
- arr[index] = value;
- }
- }
- void print() {
- for (int i = 0; i < size; i++) {
- cout << arr[i] << " ";
- }
- cout << endl;
- }
- void sort() {
- for (int k = 0; k < size; k++) {
- for (int j = 0; j < size - 1; j++) {
- if (arr[j] > arr[j + 1]) {
- T temp = arr[j];
- arr[j] = arr[j + 1];
- arr[j + 1] = temp;
- }
- }
- }
- }
- private:
- static const size_t size = 5;
- T arr[size]{}; // без фигурных скобок массив не будет инициализирован значениями по умолчанию
- };
- int main() {
- cout << "Class Tempate Array" << endl << endl;
- Array<int> int_array;
- cout << "int Array initialization:" << endl;
- int_array.print();
- int size = int_array.get_size();
- for (int i = 0; i < size; i++) {
- int_array.set_item(i, rand() % 10);
- }
- cout << endl << "int Array after assignment:" << endl;
- int_array.print();
- int_array.sort();
- cout << endl << "int Array after ordering:" << endl;
- int_array.print();
- cout << endl;
- Array<string> str_array;
- cout << "str Array initialization:" << endl;
- str_array.print();
- str_array.set_item(0, "two");
- str_array.set_item(1, "seven");
- str_array.set_item(2, "zero");
- str_array.set_item(3, "four");
- str_array.set_item(4, "one");
- cout << endl << "str Array after assignment:" << endl;
- str_array.print();
- str_array.sort();
- cout << endl << "str Array after ordering:" << endl;
- str_array.print();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement