logo CodeStepByStep logo


Language/Type: C++ Grid collections
Related Links:
Author: Eric Roberts and Marty Stepp (on 2016/06/16)

Write a function named reshape that accepts three parameters: A reference to a Grid of integers, and two integers for a row and column, and resizes the grid while retaining its data in a particular format. The resize method in the Grid class resets the dimensions of the grid but also initializes every element of the grid to its default value. Your function should resize the grid but fill in the data from the original grid by copying elements in the standard row-major order (left-to-right/top-to-bottom). For example, if a variable myGrid initially contains the following values:

       col 0   1   2   3
row  0  {{ 1,  2,  3,  4},
     1   { 5,  6,  7,  8},
     2   { 9, 10, 11, 12}}

Then calling the function reshape(myGrid, 4, 3); should change the dimensions and contents of myGrid as follows:

       col 0   1   2
row  0  {{ 1,  2,  3},
     1   { 4,  5,  6},
     2   { 7,  8,  9},
     3   {10, 11, 12}}

If the new grid does not include enough space for all of the original values, the values at the bottom of the grid are simply dropped. For example, if you call reshape(myGrid, 2, 5); there is no room for the last two elements, so the new grid will look like this:

       col 0   1   2   3   4
row  0  {{ 1,  2,  3,  4,  5},
     1   { 6,  7,  8,  9, 10}}

Conversely, if there are not enough elements in the original grid to fill the available space, the entries at the end should simply retain their default values.

Type your solution here:

This is a function problem. Write a C++ function as described. Do not write a complete program; just the function(s) above.

You must log in before you can solve this problem.

Log In

If you do not understand how to solve a problem or why your solution doesn't work, please contact your TA or instructor.
If something seems wrong with the site (errors, slow performance, incorrect problems/tests, etc.), please

Is there a problem? Contact a site administrator.

© Marty Stepp, all rights reserved.