/*************************************************************
**
** 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测试结果: