假设我们有以下类:
#include <vector>
class Matrix {
private:
std::vector<std::vector<int>> data;
};
首先,我建议您实现一个默认构造函数:
#include <vector>
class Matrix {
public:
Matrix(): data({}) {}
private:
std::vector<std::vector<int>> data;
};
此时我们可以按照以下方式创建Matrix实例:
Matrix one;
下一个战略步骤是实现一个 `Reset` 方法,它接受两个整数参数,分别指定矩阵的新行数和列数:
#include <vector>
class Matrix {
public:
Matrix(): data({}) {}
Matrix(const int &rows, const int &cols) {
Reset(rows, cols);
}
void Reset(const int &rows, const int &cols) {
if (rows == 0 || cols == 0) {
data.assign(0, std::vector<int>(0));
} else {
data.assign(rows, std::vector<int>(cols));
}
}
private:
std::vector<std::vector<int>> data;
};
此时,Reset
方法会更改2D矩阵的尺寸为给定的尺寸并重置其所有元素。稍后我将向您展示为什么我们可能需要这样做。
我们可以创建并初始化我们的矩阵:
Matrix two(3, 5);
让我们为矩阵添加信息方法:
#include <vector>
class Matrix {
public:
Matrix(): data({}) {}
Matrix(const int &rows, const int &cols) {
Reset(rows, cols);
}
void Reset(const int &rows, const int &cols) {
data.resize(rows);
for (int i = 0; i < rows; ++i) {
data.at(i).resize(cols);
}
}
int GetNumRows() const {
return data.size();
}
int GetNumColumns() const {
if (GetNumRows() > 0) {
return data[0].size();
}
return 0;
}
private:
std::vector<std::vector<int>> data;
};
此时我们可以获取一些琐碎的矩阵调试信息:
#include <iostream>
void MatrixInfo(const Matrix& m) {
std::cout << "{ \"rows\": " << m.GetNumRows()
<< ", \"cols\": " << m.GetNumColumns() << " }" << std::endl;
}
int main() {
Matrix three(3, 4);
MatrixInfo(three);
}
此时我们需要的第二个类方法是
At
。它是用于获取私有数据的一种getter方法:
#include <vector>
class Matrix {
public:
Matrix(): data({}) {}
Matrix(const int &rows, const int &cols) {
Reset(rows, cols);
}
void Reset(const int &rows, const int &cols) {
data.resize(rows);
for (int i = 0; i < rows; ++i) {
data.at(i).resize(cols);
}
}
int At(const int &row, const int &col) const {
return data.at(row).at(col);
}
int& At(const int &row, const int &col) {
return data.at(row).at(col);
}
int GetNumRows() const {
return data.size();
}
int GetNumColumns() const {
if (GetNumRows() > 0) {
return data[0].size();
}
return 0;
}
private:
std::vector<std::vector<int>> data;
};
常量At
方法接受行号和列号,返回对应矩阵单元格中的值:
#include <iostream>
int main() {
Matrix three(3, 4);
std::cout << three.At(1, 2);
}
第二个与第一个相同参数的非常量
At
方法返回对应矩阵单元格中值的引用。请注意,这里的返回值是
引用而不是原始值。
#include <iostream>
int main() {
Matrix three(3, 4);
three.At(1, 2) = 8;
std::cout << three.At(1, 2);
}
最后,让我们实现 >>
运算符:
#include <iostream>
std::istream& operator>>(std::istream& stream, Matrix &matrix) {
int row = 0, col = 0;
stream >> row >> col;
matrix.Reset(row, col);
for (int r = 0; r < row; ++r) {
for (int c = 0; c < col; ++c) {
stream >> matrix.At(r, c);
}
}
return stream;
}
然后进行测试:
#include <iostream>
int main() {
Matrix four;
MatrixInfo(four);
std::cin >> four;
MatrixInfo(four);
}
可以随意添加超出范围的检查。希望这个例子能够帮助您 :)
matrix
。 - elyashivmatrix
已经被初始化了。 - Luchian Grigore