// sample code showing two-dimensional arrays with [] and vector<> #include #include #include using namespace std; int constexpr WIDTH = 8, HEIGHT = 4; // filling both types - these illustrate prototypes for 2d arrays // Like all arrays, if you fill in the first dimension, that size is ignored. However, // the sizes of all *other* dimensions are required. void fill(int matrix[][WIDTH]); // initialize table to sum of indices of each element // The vector solution has no special rules; they are just objects (though a typedef // would likely be useful here) void fill(vector> &); // initialize table to product of indices of each elt. // illustrates declearing a 2d array: HEIGHT rows, each row with WIDTH elements void test_plain_2d_array() { int plain_array[HEIGHT][WIDTH]; // note the two dimensions listed separately // warning: writing [HEIGHT, WIDTH] would give *just* WIDTH (, as an operator) fill(plain_array); // calls array version; arrays are passed by reference! // write it out to confirm the data was set: cout << "Array-based table (each element is the sum of its indices):" << endl; for(int row = 0; row < HEIGHT; ++row) { for(int col = 0; col < WIDTH; ++col) // setw makes each element be written in 3 spaces and must be inserted // into the output stream before each element (it resets after // something is printed) cout << " " << setw(3) << plain_array[row][col]; cout << endl; } } void fill(int matrix[][WIDTH]) { for(int row = 0; row < HEIGHT; ++row) for(int col = 0; col < WIDTH; ++col) matrix[row][col] = row + col; } // illustrates creating a vector of vectors. void test_vector_based_2d_table() { vector> vect(HEIGHT); // HEIGHT vectors, each will have size 0 for(int i = 0; i < HEIGHT; ++i) vect[i].resize(WIDTH); // resize each row to size WIDTH fill(vect); // call vector version, noting the parameter is passed by reference cout << "Vector-based table (each element is the product of its indices):" << endl; for(int row = 0; row < HEIGHT; ++row) { for(int col = 0; col < WIDTH; ++col) // use .at() to reference element, though [] would work as well! // setw makes each element be written in 3 spaces (right-justified) cout << " " << setw(3) << vect.at(row).at(col); cout << endl; } } void fill(vector> &vect) { for(int row = 0; row < HEIGHT; ++row) for(int col = 0; col < WIDTH; ++col) vect[row][col] = row * col; } int main() { test_plain_2d_array(); cout << "----------------------------------------" << endl; test_vector_based_2d_table(); return 0; }