I am writing a matrix manipulation class in C++ as a course project. I want the syntax to be as close to MATLAB as possible. I wish to implement a constructor for the matrix which allows me to do something like what is shown below:
Matrix X(3,3) = {1, 2, 3, 4, 5, 6, 7, 8, 9};
// [1 2 3]
// X = [4 5 6]
// [7 8 9]
I have tried using an initializer_list
constructor but that only allows me to do:
Matrix X(3,3,{1, 2, 3, 4, 5, 6, 7, 8, 9});
Here's my code for this constructor:
Matrix::Matrix(size_t row, size_t col) : nrow(row), ncol(col), len(row*col) {
mat = std::unique_ptr<double[]>(new double[len]);
}
void Matrix::operator= (std::initializer_list<double> list) {
if (list.size() != len)
throw std::length_error("Sizes of matrix and initializer list do not match");
auto it = list.begin();
for (int i = 0; it != list.end(); ++i, ++it)
mat[i] = *it;
}
Matrix::Matrix(size_t row, size_t col, std::initializer_list<double> list) : Matrix::Matrix(row, col) {
*this = list;
}
I need suggestions on how to implement the first one.