-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDynamic2DArray.h
93 lines (79 loc) · 1.91 KB
/
Dynamic2DArray.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
// Muhammad Ali Khalid
#ifndef CPP_LIBRARIES_DYNAMIC2DARRAY_H
#define CPP_LIBRARIES_DYNAMIC2DARRAY_H
#include <iostream>
using namespace std;
template<class T>
class Dynamic2DArray {
private:
T **ptr;
int rows;
int cols;
public:
Dynamic2DArray() {
ptr = nullptr;
rows = 0;
cols = 0;
}
Dynamic2DArray(int rows, int cols) {
if (rows <= 0) {
cout << "Invalid rows" << endl;
exit(0);
}
if (cols <= 0) {
cout << "Invalid cols" << endl;
exit(0);
}
this->rows = rows;
this->cols = cols;
ptr = new T *[rows];
for (int i = 0; i < rows; i++) {
ptr[i] = new T[cols];
}
}
~Dynamic2DArray() = default;
int getRows() {
return rows;
}
int getCols() {
return cols;
}
// Taking input from user to fill array
void fillArray() {
cout << "Enter values" << endl;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cout << "Row " << i + 1 << " col " << j + 1 << ": ";
cin >> ptr[i][j];
}
}
}
void displayArray() {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cout << ptr[i][j] << " ";
}
cout << endl;
}
}
// Changing rows into cols
void transpose() {
T **newPtr = new T *[rows];
for (int i = 0; i < rows; i++) {
newPtr[i] = new T[cols];
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
newPtr[i][j] = ptr[j][i];
}
}
ptr = newPtr;
}
void deleteArray() {
for (int i = 0; i < rows; i++) {
delete[] ptr[i];
}
delete[] ptr;
}
};
#endif //CPP_LIBRARIES_DYNAMIC2DARRAY_H