您的位置:首页 > 其它

用vector编写一个矩阵模板

2017-01-07 12:50 344 查看
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;
};这样就实现了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐