矩阵martix类模板


参考数据结构与算法分析---C++描述,扩展实现矩阵类模板。


matrix.h

#pragma once

#include 

template 

class Matrix {
public:
	
	Matrix(int rows, int cols) :array(rows)
	{
		for (auto & thisRow : array)
			thisRow.resize(cols);
	}

	Matrix(std::vector> v ) : array(v) { }

	Matrix(std::vector> &&v ) : array(std::move(v)) { }

	const std::vector & operator[] (int row) const { return array[row]; }

	std::vector & operator[] (int row) { return array[row]; }

	const std::vector> & operator = (std::vector>  arr) { array = arr; return array; }
			



	size_t numrows() const { return array.size(); }

	size_t numcols() const { return numrows() ? array[0].size() : 0; }
private:
	std::vector> array;

}; 
  

main.cpp



#include 

#include "matrix.h"

using namespace std;

int main()
{
	vector> a = { {1,2,3,4,5.0},
								 {2,3,4,5,6.1},
								 {3,4,5,6,7.1},
								 {4,5,6,7,8.2},
							   };
	Matrix arr(4, 5);
	arr = a;

	cout <<"numrows :  " << arr.numrows() << endl;
	cout << "numcols : " <<  arr.numcols() << endl;

	for(auto inch: arr[1])
		cout << inch << " " ;
	cout << endl;
	cout << arr[3][0] << endl;

	return 0;
}
 
  

你可能感兴趣的:(数据结构与算法)