|
|
|
@ -0,0 +1,44 @@
|
|
|
|
|
#ifndef ARRAY2D_HPP
|
|
|
|
|
#define ARRAY2D_HPP
|
|
|
|
|
|
|
|
|
|
#include <iostream>
|
|
|
|
|
#include <stdexcept>
|
|
|
|
|
// 这里仅以int二维数组为例,扩展为类模板很容易
|
|
|
|
|
|
|
|
|
|
class Array2D
|
|
|
|
|
{
|
|
|
|
|
int **arr; // 指针数组退化为二级指针
|
|
|
|
|
const int row, col; // 二维数组的行和列
|
|
|
|
|
public:
|
|
|
|
|
Array2D(int _row, int _col) : row{_row}, col{_col}
|
|
|
|
|
{
|
|
|
|
|
// 先申请行,再申请列
|
|
|
|
|
arr = new int *[row]; // 设置行 每个元素都是int *
|
|
|
|
|
for (int i{0}; i < row; ++i)
|
|
|
|
|
arr[i] = new int[col];
|
|
|
|
|
}
|
|
|
|
|
~Array2D()
|
|
|
|
|
{
|
|
|
|
|
// 注意释放的次序!
|
|
|
|
|
for (int i{0}; i < row; ++i)
|
|
|
|
|
delete[] arr[i];
|
|
|
|
|
delete[] arr;
|
|
|
|
|
}
|
|
|
|
|
void print()
|
|
|
|
|
{
|
|
|
|
|
for (int i{0}; i < row; ++i)
|
|
|
|
|
{
|
|
|
|
|
for (int j{0}; j < col; ++j)
|
|
|
|
|
std::cout << arr[i][j] << '\t';
|
|
|
|
|
std::cout << '\n';
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
int *operator[](int i) // 重载[],允许暴露内部数据
|
|
|
|
|
{
|
|
|
|
|
if (i < 0 || i >= row)
|
|
|
|
|
throw std::out_of_range{"数组行下标越界\n"};
|
|
|
|
|
return arr[i];
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
#endif
|