Vectors (2D)
Write a function named
double
s) 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 print1 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 (ofdouble
s) 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
vector<vector<double>> M; M = {{1, 2}, {3, 4}, {5, 6}}; vector<vector<double>> N = transpose(M);
the function call
print(N)
should print1 3 5 2 4 6
Notice that each row of
M
becomes a column ofN
.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; }