参考数据结构与算法分析---C++描述,扩展实现矩阵类模板。
matrix.h
#pragma once
#include <vector>
template <typename Object>
class Matrix {
public:
Matrix(int rows, int cols) :array(rows)
{
for (auto & thisRow : array)
thisRow.resize(cols);
}
Matrix(std::vector<std::vector<Object>> v ) : array(v) { }
Matrix(std::vector<std::vector<Object>> &&v ) : array(std::move(v)) { }
const std::vector<Object> & operator[] (int row) const { return array[row]; }
std::vector<Object> & operator[] (int row) { return array[row]; }
const std::vector<std::vector<Object>> & operator = (std::vector<std::vector<Object>> 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<std::vector<Object>> array;
};
main.cpp
#include <iostream>
#include "matrix.h"
using namespace std;
int main()
{
vector<vector<double>> 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<double> 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;
}