/*--------------------------------------------------
试编写一个函数ChangeSize2D 来改变一个二维数组的大小
---------------------------------------------*/
#include <iostream>
using namespace std;
const int ROWS = 5;
const int COLS = 10;
template <class T> void DeleteSize2D(T **ch1, int rows);
template <class T>
T** ChangeSize2D(T **ch1, int rows, int cols)
{
T **ch2 = new T* [rows];
for (int i = 0; i < rows; i++)
ch2[i] = new T [cols];
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
ch2[i][j] = ch1[i][j];
DeleteSize2D(ch1, ROWS);
return ch2;
}
template <class T>
T** CreateSize2D(T **ch1, int rows, int cols)
{
ch1 = new T* [rows];
for (int i = 0; i < rows; i++)
ch1[i] = new T [cols];
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
ch1[i][j] = 'A'+i+j;
return ch1;
}
template <class T>
void DeleteSize2D(T **ch1, int rows)
{
for (int i = 0; i < rows; i++)
delete [] ch1[i];
delete [] ch1;
ch1 = 0;
}
template <class T>
void ShowSize2D(T **ch1, int rows, int cols)
{
cout << "The Size2DArray = \n{\n";
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
cout << ch1[i][j] << ", ";
cout << endl;
}
cout << "}\n";
}
int main()
{
int rows, cols;
char **ch1 = 0;
ch1 = CreateSize2D(ch1, ROWS, COLS);
ShowSize2D(ch1, ROWS, COLS);
cout << "\nPlease change rows and cols the Size2DArray:\n";
cin >> rows >> cols;
if (rows == ROWS || cols == COLS)
cout << "The Size2DArray needn't change!\n";
else if (rows > ROWS || cols > COLS)
{
cout << "The rows or cols is error!\n";
exit(1);
}
else
{
ch1 = ChangeSize2D(ch1, rows, cols);
ShowSize2D(ch1, rows, cols);
}
DeleteSize2D(ch1, rows);
return 0;
}