Week 7

Vectors (2D)

Exercise 7.1

Write a function named print that prints a 2D vector (of doubles) as a matrix. You may assume that each element of the vector has the same size and that the vector and each of its elements are nonempty.

For example, given the code

vector<vector<double>> M;

M = {{1, 2},
     {3, 4},
     {5, 6}};

the function call print(M) should print

1 2
3 4
5 6

Solution

Here is one possible solution.

void print(const vector<vector<double>>& A) {
    for (int i = 0; i < A.size(); ++i) {
        for (int j = 0; j < A[i].size(); ++j) {
            cout << A[i][j] << ' ';
        }
        cout << '\n';
    }
}

Alternative solution

Here is another possible solution, using a range-based for loop.

void print(const vector<vector<double>>& A) {
    for (const vector<double>& row : A) {
        for (const double& entry : row) {
            cout << entry << ' ';
        }
        cout << '\n';
    }
}

Exercise 7.2

Write a function named transpose that takes a 2D vector (of doubles) and returns its transpose. You may assume that each element of the vector has the same size and that the vector and each of its elements are nonempty.

For example, given the print function from Exercise 7.1 and the code

vector<vector<double>> M;

M = {{1, 2},
     {3, 4},
     {5, 6}};

vector<vector<double>> N = transpose(M);

the function call print(N) should print

1 3 5
2 4 6

Notice that each row of M becomes a column of N.

Hint: The fill constructor for vector may be useful, along with the solution to Exercise 7.1.

Solution

Here is one possible solution.

vector<vector<double>> transpose(const vector<vector<double>>& A) {
    vector<vector<double>> B(A[0].size(), vector<double>(A.size()));

    for (int i = 0; i < A.size(); ++i) {
        for (int j = 0; j < A[i].size(); ++j) {
            B[j][i] = A[i][j];
        }
    }

    return B;
}