![]() |
#2
rjsp2025-04-15 08:33
|

class matrix {
private:
vector<vector<float>>data;
int rows;
int cols;
public:
matrix(int _rows, int _cols) :rows(_rows), cols(_cols), data(rows, vector<float>(cols, 0.0f)) {}
matrix(const vector<vector<float>>& input) :data(input), rows(input.size()), cols(input[0].size()) {}
int getCols()const { return cols; }
int getRows()const { return rows; }
void setValue(int i, int j, float value) { data[i][j] = value; }
float& operator()(int i, int j) { return data[i][j]; }
const float& operator()(int i, int j)const { return data[i][j]; }
vector<float> operator *(const vector<float>& vec) const {
if (cols != vec.size()) {
throw invalid_argument("Matrix and vector dimensions do not match!");
}
vector<float> result(rows, 0.0f);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result[i] += data[i][j] * vec[j];
}
}
return result;
}
};
matrix mat(3,3);
mat(0,0) = 1.0f;
为什么我这样写通过mat(0,0)赋值会报错,通过setValue同样会报错,把data从private拿到public又不会报错了 private:
vector<vector<float>>data;
int rows;
int cols;
public:
matrix(int _rows, int _cols) :rows(_rows), cols(_cols), data(rows, vector<float>(cols, 0.0f)) {}
matrix(const vector<vector<float>>& input) :data(input), rows(input.size()), cols(input[0].size()) {}
int getCols()const { return cols; }
int getRows()const { return rows; }
void setValue(int i, int j, float value) { data[i][j] = value; }
float& operator()(int i, int j) { return data[i][j]; }
const float& operator()(int i, int j)const { return data[i][j]; }
vector<float> operator *(const vector<float>& vec) const {
if (cols != vec.size()) {
throw invalid_argument("Matrix and vector dimensions do not match!");
}
vector<float> result(rows, 0.0f);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result[i] += data[i][j] * vec[j];
}
}
return result;
}
};
matrix mat(3,3);
mat(0,0) = 1.0f;