练习:试编写一个函数ChangeSize2D 来改变一个二维数组的大小

/*--------------------------------------------------
试编写一个函数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;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值