Multidimensional Arrays Vectors of Vectors When One Is
- Slides: 6
Multidimensional Arrays Vectors of Vectors When One Is Not Enough
Two Dimensional Array Basics matrices, tables and similar information is often naturally represented by a two-dimensional array first index – row second index - column declaration: basic. Type array. Name[rows][columns]; example int a[3][4]; accessing a[0][1] = 23; cout << a[1][3]; c[2][4]+=55; either index out of range is still an error a[2][4] = 55; // error larger dimensions are possible: int b[10][100][200];
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] << ” ”;
Arrays and Functions if multidimensional array is used as parameters, all but first dimension have to be stated the first dimension can be passed as a separate parameter const int WIDTH=2; void print. Array(int c[][WIDTH], int length){ for (int i=0; i < length; ++i) for (int j=0; j < WIDTH; ++j) cout << c[i][j] << ” ”; }
Vectors of Vectors alternative to multidimensional arrays outer vector’s type is declared to be a vector<vector<int> > a; note the space between closing angle brackets! inner vectors can then be added to the outer vector<int> row(width); for(int i=0; i < length; ++i) a. push_back(row); 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] << ” ”; vectors retain all advantage over arrays: has extra functions, carry size, can pass by value/return, can change size on demand moreover: can create ragged (jagged) arrays – rows can vary in size
Review Questions Why are multidimensional arrays necessary? How does one declare a two-dimensional array? what is the first index? the second index? How does one access an element of multidimensional array? Why are nested loops useful with multidimensional arrays? How is a multidimensional array passed as a parameter to a function? What is a vector of vectors? How does one declare a vector of vectors? Initialize it? How are individual elements of a vector of vectors accessed? What are the advantages of a vector of vectors over a multidimensional array? What is a ragged/jagged array?