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; }