Presentation is loading. Please wait.

Presentation is loading. Please wait.

Multidimensional Arrays Vectors of Vectors When One Is Not Enough.

Similar presentations


Presentation on theme: "Multidimensional Arrays Vectors of Vectors When One Is Not Enough."— Presentation transcript:

1 Multidimensional Arrays Vectors of Vectors When One Is Not Enough

2 Two Dimensional Array Basics l matrices, tables and similar information is often naturally represented by a two-dimensional array n first index – row n second index - column l declaration: basicType arrayName[rows][columns]; example int a[3][4]; l accessing a[0][1] = 23; cout << a[1][3]; c[2][4]+=55; l either index out of range is still an error a[2][4] = 55; // error larger dimensions are possible: int b[10][100][200]; 2

3 Two Dimensional Arrays in Loops nested loops are useful with multidimensional arrays for (int i=0; i < length; ++i) for (int j=0; j < width; ++j) cout << a[i][j] << ” ”; 3

4 Arrays and Functions l if multidimensional array is used as parameters, all but first dimension have to be stated l the first dimension can be passed as separate parameter const int WIDTH=2; void printArray(int c[][WIDTH], int length){ for (int i=0; i < length; ++i) for (int j=0; j < WIDTH; ++j) cout << c[i][j] << ” ”; } 4

5 Vectors of Vectors l alternative to multidimensional arrays l outer vector’s type is declared to be a vector vector > a; l inner vectors can then be added to the outer vector vector row(width); for(int i=0; i < length; ++i) a.push_back(row); l vector elements can be accessed as in array for (int i=0; i < length; ++i) for (int j=0; j < width; ++j) cout << a[i][j] << ” ”; l vectors retain all advantage over arrays: has extra functions, carry size, can pass by value/return, can change size on demand l moreover: can create ragged (jagged) arrays – rows can vary in size 5

6 Review Questions l Why are multidimensional arrays necessary? l How does one declare a two-dimensional array? l What is the first index? the second index? l How does one access an element of multidimensional array? l Why are nested loops useful with multidimensional arrays? l How is multidimensional array passed as a parameter to a function? l What is vector of vectors? l How does one declare a vector of vectors? Initialize it? l How are individual elements of a vector of vectors accessed? l What are the advantages of a vector of vectors over multidimensional array? l What is ragged/jagged array? 6


Download ppt "Multidimensional Arrays Vectors of Vectors When One Is Not Enough."

Similar presentations


Ads by Google