如何在二维数组中存储值?

How to store values ​in 2-D array?

本文关键字:存储 二维数组      更新时间:2023-10-16
#include<string>
#include<vector>
#include<iostream>
using namespace std;
class CMatrix
{
private:
string name;
float** matrix;
int nRow;
int nCol;
int nElement;  //총 element 수
public:
CMatrix() {
this->name = "Anonymous";
this->nRow = 4;
this->nCol = 4;
matrix = new float* [nRow];
for (int i = 0; i < nRow; i++)
matrix[i] = new float[nCol];
for (int i = 0; i < nRow; i++)
for (int j = 0; j < nCol; j++)
matrix[i][j] = 0;
}
CMatrix(string _name, int _nRow, int _nCol) {
this->nRow = _nRow;
this->nCol = _nCol;
this->name = _name;
matrix = new float* [nRow];
for (int i = 0; i < nRow; i++)
matrix[nRow] = new float[nCol];
}
CMatrix(CMatrix& n1);
~CMatrix() {};
void setElement() {
cout << "<Enter the elements of A>" << endl << ">>";
for (int i = 0; i < nRow; i++) {
for (int j = 0; j < nCol; j++)
cin >> matrix[i][j];
}
}
void printMatrixinfo() {
cout << this->name << '(' << this->nRow << ", " << this->nCol << ", " << nRow * nCol << ") " <<             
endl;
for (int i = 0; i < nRow; i++) {
cout << "[ ";
for (int j = 0; j < nCol; j++)
cout << matrix[nRow][nCol] << " ";
cout << "] ";
cout << endl;
}
}
string getName() {
return this->name;
}
};
void getData(string& _name, int& _nRow, int& _nCol) {
cout << "<Enter the name , # of rows, # of cols" << endl << ">>";
cin >> _name >> _nRow >> _nCol;
}
int main() {
string name;
int nRow, nCol;
getData(name, nRow, nCol);
CMatrix x1(name, nRow, nCol);
x1.setElement();
x1.printMatrixinfo();
cout << endl;
return 0;
}

首先,我们通过函数getData将值保存在namenRownCol中。然后我们调用CMatrix x1 (name, nRow, nCol)来初始化x1namenRownCol。然后,我尝试通过x1.setElement()函数放置一个元素,但不断收到错误。如果您让我知道我错在哪里,我将不胜感激。

如果还添加错误的输出,可能会有所帮助。除此之外,我看不出为什么你会使用原始指针,或者不使用std::vector<>或者只是简单地使用多维数组。此外,您有内存泄漏,请确保删除类析构函数中矩阵的所有new初始化值。

编辑:我看到了您对问题和评论的编辑。对代码的编辑仍然有一个错误,但它不在setElement()中,而是在void printMatrixinfo()中,特别是行:

cout << matrix[nRow][nCol] << " ";

nRow 和 nCol 是越界的。 从您的代码结构来看,我想您想在这里使用cout << matrix[i][j] << " ";

再说一次,如果这是使用原始指针的问题条件,请不要忘记在析构函数中删除矩阵(您的~CMatrix()不应该为空!