c++学习笔记(23)Matrix 的实现

这篇博客详细介绍了如何使用C++中的vector嵌套来实现Matrix类,包括基本操作的定义和实现,如析构函数、复制赋值和复制构造函数等。
摘要由CSDN通过智能技术生成

利用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;
}


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值