template<typename T>
class Array2D {
private:
vector<vector<T>> data;
public:
Array2D(int rows, int cols) : data(rows, vector<T>(cols)) {
assert((rows > 0 && cols > 0));
}
Array2D(const Array2D<T> &other) : data(other.data) {}
Array2D &operator=(const Array2D<T> &other) {
this->data = other.data;
return *this;
}
Array2D(Array2D<T> &&other) : data(move(other.data)) {}
const vector<T> &operator[](int m) const {
return data[m];
}
vector<T> &operator[](int m) {
return const_cast<vector<T> &>(data[m]);
}
int first_size() const {
return data.size();
}
int second_size() const {
if (data.empty()) {
return 0;
}
return data[0].size();
}
void print() {
for (int i = 0; i < first_size(); ++i) {
for (int j = 0; j < second_size(); ++j) {
cout << data[i][j] << "\t";
}
cout << endl;
}
}
};
template<typename T>
class Array2DManager {
public:
auto static getInstance(int m, int n) {
return Array2D<T>(m, n);
}
};
int main() {
Array2DManager<int> am;
auto data = am.getInstance(3, 7);
data = am.getInstance(1, 5);
for (int i = 0; i < data.first_size(); ++i) {
for (int j = 0; j < data.second_size(); ++j) {
data[i][j] = i * data.second_size() + j;
}
}
data.print();
}
c++ 二维数组的实现
最新推荐文章于 2023-10-22 16:37:54 发布