C++矩阵模板类的实现

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

#ifndef MATRIX_H
#define MATRIX_H

#include <vector>

/**
 * 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 T>
class Matrix
{
public:
	Matrix(int rows, int cols) : _array(rows)
	{
		for (auto & thisRow : _array)
			thisRow.resize(cols);
	}
	// copy constructor.
	Matrix(std::vector<std::vector<T>> src) : _array{ src }
	{}
	// move constructor.
	Matrix(std::vector<std::vector<T>> && src) : _array{ std::move(src) }
	{}

	// overload operator [].
	const std::vector<T> & operator[](std::size_t row) const
	{
		return _array[row];
	}
	std::vector<T> & 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<std::vector<T>> _array;
};

#endif // MATRIX_H

 

示例程序:

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

#include "matrix.h"
#include <iostream>
using namespace std;
#include <cstdlib>
#include <cstdio>

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

int main()
{
	Matrix<int> 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测试结果:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值