vector可以写二维以上的矩阵么?这个问题我在看完vector和string的时候就在思索。应该怎么写?采用和二维数组类似的思想,如果vector容纳的vector不就可以了,而且访问操作要比数组方便不少。程序如下:
#include<iostream>
#include<vector>
using namespace std;
template<typename T> //模板
class matrix {
public:
matrix(int rows, int cols) :arr(rows)
{
/*for (rsize_t t = 0;t < rows;t++)
arr[t].resize(cols);*/
for (auto &thisRow : arr) //auto自动推断
thisRow.resize(cols);
}
matrix(vector<vector<T>> v):arr{v} //复制拷贝构造函数
{}
matrix(vector<vector<T>> &&v) :arr{ std::move(v) }//移动拷贝构造函数
{}
const vector<T> &operator[](int row)const//重载下标引用
{
return arr[row];
}
vector<T>& operator[](int row)
{
return arr[row];
}
int numrows()const //行数
{
return arr.size();
}
int numcols()const //列数
{
return numrows() ? arr[0].size() : 0;
}
private:
vector<vector<T>>arr;
};
这样就实现了。