Groupwork: CPS 100E

Removing zeros from vectors, arrays, matrices


Write each function below that removes all the zeros from a vector or a matrix. The order of the other elements should remain unchanged.

Vector

For example, removing zeros from a vector is shown below.


    1 2 0 3 0 0 4 0 0 0 5 0        1 2 3 4 5

         before                       after
The function has two parameters: the vector and the number of elements in the vector.
    void RemoveZeros(Vector<int> & list, int & numElts)
    // precondition: numElts = # of elements in list
    // postcondition: numElts = # of elements in list, list has no zeros

Matrix

Remove zeros from a matrix as shown below. There might be some problems with this, think about it.

   1 2 0 3 0            1 2 3 4 5
   0 4 5 0 0            6 7 8 9 1
   0 0 6 0 7
   0 8 9 1 0

      before              after



void RemoveZeros(Matrix<int> & mat, int & rows, int  cols)
// precondition: mat is a rows x cols matrix of ints
// postcondition: all zeros removed, mat has cols columns (unchanged
//                from entry), the # of rows may change