用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;
};这样就实现了。
#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;
};这样就实现了。
相关文章推荐
- 请编写一个算法,若MxN矩阵中某个元素为0,则将其所在的行与列清零。 给定一个MxN的int[][]矩阵(C++中为vector>)mat和矩阵的阶数n,请返回完成操作后的int[][]矩阵(C++中
- 清除行列 请编写一个算法,若N阶方阵中某个元素为0,则将其所在的行与列清零。 给定一个N阶方阵int[][](C++中为vector<vector><int>>)mat和矩阵的阶数n,请返回完成操
- 习题一:编写一个模板函数Input,它要求用户输入一个非负数
- 编写模板的一个问题
- 求一个矩阵最大子矩阵的算法模板
- 假设有两个包含整数的vector对象,编写一段程序,检验其中一个vector对象是否是另一个的前缀。
- 从易到难编写C++程序,(8)问题:实现一个矩阵类
- 给定一个正整数和负整数组成的N*N矩阵,编写代码找出元素总和最大的子矩阵。
- 编写一段程序,将含有整数元素的vector对象复制给一个整形数组;
- 编写一个函数(参数用数组指针)将一个3×3矩阵转置。
- 一个矩阵的类与矩阵连乘模板
- vector用作函数模板形参时出现的一个错误
- 编写一个简单的 jQuery 插件(模板)
- 编写程序输入一个n*n的矩阵,求出两条对角线元素值之和(注意把输入的元素写入二维数组的方式)
- //编写程序判断一个vector<int>容器所包含的元素是否与一个list<int>容器的完全相同
- dll中导出一个类.导出模板STL.vector,遭遇的警告.
- 一个简单的矩阵类编写实例
- 编写程序从标准输入设备读入的元素数据建立一个int型vector对象,然后动态创建与该vector大小一致的数组,把vector对象的所有元素复制给该数组
- 数据结构第5章例题 若矩阵Am×n中存在某个元素aij满足:aij是第i行中的最小值且是第j列中的最大值,则称该元素为矩阵A的一个鞍点。试编写一个算法,找出A中的所有鞍点。