logo CodeStepByStep logo

unflatten

Language/Type: C++ Grid Vector collections
Related Links:

Write a method named unflatten that accepts three parameters: a reference to a Vector of integers, and a number of rows and columns. Your method should convert the vector into a Grid with the given number of rows and columns, where values are transferred in row-major order into the grid. For example, if the given vector is declared:

Vector<int> v {3, 8, 12, 2, 9, 17, 43, -8, 46, 203, 14, 97};

Then the call of unflatten(v, 4, 3) should return the following grid:

{{  3,   8,  12},
 {  2,   9,  17},
 { 43,  -8,  46},
 {203,  14,  97}}

The call of unflatten(v, 6, 2) should return the following grid:

{{  3,   8},
 { 12,   2},
 {  9   17},
 { 43,  -8},
 { 46, 203},
 { 14,  97}}

If the vector's contents do not fit exactly into a grid of the given dimensions, your method should throw an int exception. Your code should work for a vector of any size. Your method should not modify the vector that is passed in.

Function: Write a C++ function as described, not a complete program.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.