• 欢迎访问开心洋葱网站,在线教程,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站,欢迎加入开心洋葱 QQ群
  • 为方便开心洋葱网用户,开心洋葱官网已经开启复制功能!
  • 欢迎访问开心洋葱网站,手机也能访问哦~欢迎加入开心洋葱多维思维学习平台 QQ群
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏开心洋葱吧~~~~~~~~~~~~~!
  • 由于近期流量激增,小站的ECS没能经的起亲们的访问,本站依然没有盈利,如果各位看如果觉着文字不错,还请看官给小站打个赏~~~~~~~~~~~~~!

C++动态二维数组示范

OC/C/C++ 水墨上仙 2290次浏览

C++动态二维数组演示

#include <iostream>
#include <string>
using namespace std;
void allocate_2D(int **&List, int x, int y, int ycur, int xmax)
{
	//makes a temp for saving data that was in the array
	int **TEMP = List; 
	//creates a new array to the right size
	List = new int*[x];
	for( int i = 0; i < x; i++ )
	{
		List[i] = new int[y];
		for( int j = 0; j < y; j++ )
		{
			List[i][j] = 0;
		}
	}
	//copies info into newly allocated array
	for( int i = 0; i < xmax; i++ )
	{
		for( int j = 0; j <= ycur; j++ )	
		{
			List[i][j] = TEMP[i][j]; 
		}
	}
	//deletes the TEMP array
	for( int i = 0; i < ycur; i++ )
	{
		delete[] TEMP[i];
		TEMP[i] = 0;
	}
	delete[] TEMP;
	TEMP = 0;
}
int main()
{
	string input;
	int xsize = 1, ysize = 1;
	int xcur = 0, ycur = 0, xmax = 0;
	int **List;
	cout << "Enter some integers (input 'r' for new row and 's' for stop):" << endl;
	while(cin >> input)
	{
		if( input == "s" ) //done entering values
			break;
		else if( input == "r" ) //add a row
		{
			ysize++;
			allocate_2D(List, xsize, ysize, ycur, xmax); //makes a new array with another row
			xcur = 0;
			ycur += 1;
		}
		else
		{
			//add a value
			xsize++;
			allocate_2D(List, xsize, ysize, ycur, xmax); //makes a new array with another column
			List[xcur][ycur] = atoi(input.c_str()); //converts input to integer and adds it to the list
			xcur++;
			if( xcur > xmax ) //keeps track of the maxium width of the array
				xmax = xcur;
		}
	}
	//outputs the array
	for( int j = 0; j <= ycur; j++ )
	{
		for( int i = 0; i < xmax; i++ )
		{
			cout << List[i][j] << " ";
		}
		cout << endl;
	}
	system("PAUSE");
	return 0;
}


开心洋葱 , 版权所有丨如未注明 , 均为原创丨未经授权请勿修改 , 转载请注明C++动态二维数组示范
喜欢 (0)
加载中……