C++矩阵模板类的实现

/*************************************************************
**
** Matrix template class.
**
** By shaoguang @ 2019-04-01.
**
*************************************************************/

#ifndef MATRIX_H
#define MATRIX_H

#include 

/**
 * https://en.cppreference.com/w/cpp/types/size_t/
 * When indexing C++ containers, such as std::string, std::vector, etc, 
 * the appropriate type is the member typedef size_type provided by such containers. 
 * It is usually defined as a synonym for std::size_t.
 **/

template 
class Matrix
{
public:
	Matrix(int rows, int cols) : _array(rows)
	{
		for (auto & thisRow : _array)
			thisRow.resize(cols);
	}
	// copy constructor.
	Matrix(std::vector> src) : _array{ src }
	{}
	// move constructor.
	Matrix(std::vector> && src) : _array{ std::move(src) }
	{}

	// overload operator [].
	const std::vector & operator[](std::size_t row) const
	{
		return _array[row];
	}
	std::vector & operator[](std::size_t row)
	{
		return _array[row];
	}

	// Rows of matrix.
	std::size_t rows() const
	{
		return _array.size();
	}

	// Cols of matrix.
	std::size_t cols() const
	{
		return rows() ? _array[0].size() : 0;
	}

private:
	std::vector> _array;
};

#endif // MATRIX_H

 

示例程序:

/*************************************************************
**
** Matrix template class demo.
**
** By shaoguang @ 2019-04-01.
**
*************************************************************/

#include "matrix.h"
#include 
using namespace std;
#include 
#include 

std::vector row1{ 1, 2, 3, 4, 5 };
std::vector row2{ 2, 3, 4, 5, 6 };
std::vector row3{ 3, 4, 5, 6, 7 };
std::vector> src{ row1, row2, row3 };

int main()
{
	Matrix matrix(src);

	for (std::size_t i = 0; i < matrix.rows(); ++i)
	{
		printf("row_%d : ", i);
		for (std::size_t j = 0; j < matrix.cols(); ++j)
			cout << matrix[i][j];
		cout << endl;
	}

	system("pause");
	return 0;
}

 MSVC15测试结果:

C++矩阵模板类的实现_第1张图片

 

你可能感兴趣的:(VC++,C++应用)