实现矩阵Matrix模板类,支持基本的数据运算。功能包括: 1.支持多种数据类型,Matrix, 2.重载运算符+、-、* 3.支持矩阵的<<,>>操作符的代码
时间: 2024-02-05 19:11:11 浏览: 97
以下是一个简单的矩阵Matrix模板类实现:
```cpp
#include <iostream>
#include <vector>
template <typename T>
class Matrix {
private:
std::vector<std::vector<T>> data;
size_t row, col;
public:
Matrix(size_t row, size_t col) : row(row), col(col) {
data.resize(row);
for (size_t i = 0; i < row; ++i) {
data[i].resize(col);
}
}
Matrix(const Matrix<T>& other) {
row = other.row;
col = other.col;
data = other.data;
}
Matrix<T>& operator=(const Matrix<T>& other) {
if (&other != this) {
row = other.row;
col = other.col;
data = other.data;
}
return *this;
}
Matrix<T> operator+(const Matrix<T>& other) const {
if (row != other.row || col != other.col) {
throw std::invalid_argument("Matrix with different size.");
}
Matrix<T> res(row, col);
for (size_t i = 0; i < row; ++i) {
for (size_t j = 0; j < col; ++j) {
res.data[i][j] = data[i][j] + other.data[i][j];
}
}
return res;
}
Matrix<T> operator-(const Matrix<T>& other) const {
if (row != other.row || col != other.col) {
throw std::invalid_argument("Matrix with different size.");
}
Matrix<T> res(row, col);
for (size_t i = 0; i < row; ++i) {
for (size_t j = 0; j < col; ++j) {
res.data[i][j] = data[i][j] - other.data[i][j];
}
}
return res;
}
Matrix<T> operator*(const Matrix<T>& other) const {
if (col != other.row) {
throw std::invalid_argument("Matrix with incompatible size.");
}
Matrix<T> res(row, other.col);
for (size_t i = 0; i < row; ++i) {
for (size_t j = 0; j < other.col; ++j) {
T& t = res.data[i][j];
t = 0;
for (size_t k = 0; k < col; ++k) {
t += data[i][k] * other.data[k][j];
}
}
}
return res;
}
friend std::ostream& operator<<(std::ostream& os, const Matrix<T>& mat) {
for (size_t i = 0; i < mat.row; ++i) {
for (size_t j = 0; j < mat.col; ++j) {
os << mat.data[i][j] << ' ';
}
os << '\n';
}
return os;
}
friend std::istream& operator>>(std::istream& is, Matrix<T>& mat) {
for (size_t i = 0; i < mat.row; ++i) {
for (size_t j = 0; j < mat.col; ++j) {
is >> mat.data[i][j];
}
}
return is;
}
};
```
使用示例:
```cpp
int main() {
Matrix<int> a(2, 3);
Matrix<int> b(3, 2);
std::cin >> a >> b;
std::cout << a + b << '\n';
std::cout << a - b << '\n';
std::cout << a * b << '\n';
return 0;
}
```
其中,Matrix<int>代表一个int类型的矩阵,可以根据需要替换为其他数据类型。在main函数中使用了输入输出流重载运算符<<,>>。
阅读全文