利用vector的嵌套实现了Matrix, 其中析构函数,还有复制赋值,复制构造函数vector 中都有,所以只是定义了一些基本的:
#include "iostream"
#include "vector"
using namespace std;
template<class T>
class Matrix
{
private:
vector<vector<T>> Array; //矩阵的创建
public:
Matrix(int rows, int cols, int line[], int num = 0):Array(rows) // 构造 num是line的个数
{
vector<int> vec;
int index = 0;
while(index<num)
{
vec.push_back(line[index]);
index++;
}
for(int i = 0; i < rows; i++)
{
Array[i].resize(cols);
for(int j = 0; j < cols; j++)
if((i+j+i*cols) < num)
Array[i][j] = vec[i+j+i*cols];
else
Array[i][j] = 0;
}
}
int Rows()const {return Array.size();} //取行数
int Cols()const {return Rows() ? Array[0].size() : 0;} //取列数
const vector<T> &operator[](int row) const //the line of a matrix
{
return Array[row];
}
vector<T> &operator[](int row)
{
return Array[row];
}
Matrix<T> operator+() const; //一元加法 //真心不知什么作用
Matrix<T> operator+(const Matrix<T>& m) const; //两个举证相加
};
template<class T>
Matrix<T> Matrix<T>::operator+(const Matrix<T>& m) const
{
if((Array.size() != m.Rows()) ||(Array[0].size() != m.Cols()))
{
cout << "the size of the two matrix is not fited";
abort();
}
Matrix<T> w(m);
for(int rows = 0; rows < Array.size(); rows++)
for(int cols = 0; cols < Array[0].size(); cols++)
{
w[rows][cols] = Array[rows][cols] + m[rows][cols];
}
return w;
}
int main()
{
//初始化一个int数组
int a[10] = {1,3,4,5,6,7,8,98,23,1};
Matrix<int> matrix(3, 5, a, 10);
Matrix<int> matrix1(3 ,5, a, 10);
matrix[1][2] = 4;
matrix[2][3] = 9;
cout << matrix[2][3];
cout << matrix[0][0];
cout << matrix.Cols();
vector<int> rowArray;
rowArray = matrix.operator [](2);
matrix1 = matrix + matrix1;
cin.get();
cin.get();
return 0;
}