我有一个类,通过使用嵌套向量模拟二维矩阵,如下所示:
在类头文件中是这样的:
template <typename T> class L1Matrix {
private:
std::vector<std::vector<T> > mat;
unsigned rows;
unsigned cols;
public:
L1Matrix(); /* emptry constructor */
L1Matrix(unsigned _rows, unsigned _cols, const T& _initial);
L1Matrix(const L1Matrix<T>& rhs);
virtual ~L1Matrix();
T& operator()(const unsigned& row, const unsigned& col);
const T& operator()(const unsigned& row, const unsigned& col) const;
}
在类声明中是这样的:
// default constructor
template<typename T>
L1Matrix<T>::L1Matrix() : rows(0), cols(0) {};
template<typename T>
L1Matrix<T>::L1Matrix(unsigned _rows, unsigned _cols, const T& _initial) {
mat.resize(_rows);
for (unsigned i=0; i<mat.size(); i++) {
mat[i].resize(_cols, _initial);
}
rows = _rows;
cols = _cols;
}
template<typename T>
L1Matrix<T>::L1Matrix(const L1Matrix<T>& rhs) {
mat = rhs.mat;
rows = rhs.get_rows();
cols = rhs.get_cols();
}
template<typename T>
std::vector<std::vector<T> >::reference L1Matrix<T>::operator()(const unsigned& row, const unsigned& col) {
return this->mat[row][col];
}
为简洁起见,我不在这里给出类实现的其余部分。
现在在主代码中,我创建了指向这个2D矩阵的指针,如下所示:
L1Matrix<bool>* arr1; // this is pointer to L1Matrix object
L1Matrix<int> arr2(XSize, YSize, 0); // L1Mtarix object
arr1 = new L1Matrix<bool>(XSize, YSize, true);
现在对于实际的l1矩阵对象arr2
,我可以像这样访问各个行和列:arr2(row,col)
,但我的问题是如何使用L1Matrix
指针对象arr1
访问类似的行和列元素?
请告诉我。由于
您应该能够使用(*arr1)(row, col)