The data type std::complex is available in C++, but for 2D matrices a template is probably needed. If the required arithmetic operations are all available with the datatype complex, only the matrix multiplication would have to be done. Matrix multiplication and, if necessary, other matrix arithmetic operations can be added quickly. However, this looks the same as for other data types.
First a general matrix template would have to be created:
template<typename T>
class Matrix {
public:
Matrix() : _rows(0), _cols(0) {};
Matrix(int rows, int cols): _rows(rows), _cols(cols), _data(rows* cols) { };
Matrix(std::initializer_list<std::initializer_list<T>> elements) :
_rows(elements.size()), _cols(elements.begin()->size()), _data(_rows* _cols)
{
int row = 0, col = 0;
for (auto row_elem : elements) {
col = 0;
for (auto val : row_elem) {
_data[row * _cols + col] = val;
++col;
}
++row;
}
}
T& operator()(int i, int j) {
if (i < 0 || i >= _rows || j < 0 || j >= _cols) {
throw std::out_of_range("Matrix index out of range");
} return _data[i * _cols + j];
}
const T& operator()(int i, int j) const {
if (i < 0 || i >= _rows || j < 0 || j >= _cols) {
throw std::out_of_range("Matrix index out of range");
} return _data[i * _cols + j];
}
int rows() const { return _rows; }
int cols() const { return _cols; }
Matrix<T> operator*(const Matrix<T>& other) const {
if (_cols != other._rows) {
throw std::invalid_argument("Number of columns of first matrix must be equal to number of rows of second matrix");
}
Matrix<T> result(_rows, other._cols);
for (int i = 0; i < _rows; i++) {
for (int j = 0; j < other._cols; j++) {
}
}
return result;
}
friend std::ostream& operator<<(std::ostream& os, const Matrix<T>& m) {
if (m._data.empty() || m._rows == 0 || m._cols == 0) {
return os << "";
}
for (int i = 0; i < m._rows; ++i) {
for (int j = 0; j < m._cols; ++j) {
os << m(i, j) << " ";
}
os << std::endl;
}
return os;
}
private:
int _rows, _cols;
std::vector<T> _data;
};
A test program could then look like this:
using namespace std::complex_literals;
typedef std::complex<double> MatComplex;
Matrix<MatComplex> A = { {1, 2i, 3}, {4i, 5, 6} };
Matrix<MatComplex> B = { {7, 8i}, {9i, 10}, {11, 12i} };
Matrix<MatComplex> C;
std::cout << "Matrix A:\n" << A << std::endl;
std::cout << "Matrix B:\n" << B << std::endl;
C = A * B;
std::cout << "Matrix C = A*B:\n" << C << std::endl;