You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
# ifndef ARRAY2D_HPP
# define ARRAY2D_HPP
# include <iostream>
# include <stdexcept>
// 这里仅以int二维数组为例, 扩展为类模板很容易
class Array2D
{
int * * arr ; // 指针数组退化为二级指针
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 ) const // 重载[],允许暴露内部数据
{
if ( i < 0 | | i > = row )
throw std : : out_of_range { " 数组行下标越界 \n " } ;
return arr [ i ] ;
}
} ;
# endif