如何在二维数组中存储值?
How to store values in 2-D array?
#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
将值保存在name
、nRow
、nCol
中。然后我们调用CMatrix x1 (name, nRow, nCol)
来初始化x1
的name
、nRow
、nCol
。然后,我尝试通过x1.setElement()
函数放置一个元素,但不断收到错误。如果您让我知道我错在哪里,我将不胜感激。
如果还添加错误的输出,可能会有所帮助。除此之外,我看不出为什么你会使用原始指针,或者不使用std::vector<>
或者只是简单地使用多维数组。此外,您有内存泄漏,请确保删除类析构函数中矩阵的所有new
初始化值。
编辑:我看到了您对问题和评论的编辑。对代码的编辑仍然有一个错误,但它不在setElement()
中,而是在void printMatrixinfo()
中,特别是行:
cout << matrix[nRow][nCol] << " ";
nRow 和 nCol 是越界的。 从您的代码结构来看,我想您想在这里使用cout << matrix[i][j] << " ";
。
再说一次,如果这是使用原始指针的问题条件,请不要忘记在析构函数中删除矩阵(您的~CMatrix()
不应该为空!
相关文章:
- 将值从二维数组输出到文本文件
- 在二维数组中查找最小值和最大值?
- 移动二维数组中的字符
- 如何正确填充在堆上分配的二维数组?
- 传递二维数组时出现问题
- 具有随机数的二维数组不会更改
- 如何在二维数组中存储值?
- 如何将 numpy 二维数组作为一种可以用C++读取的二进制格式存储在磁盘上
- C++ ->尝试逐字阅读一行文本。如何使指针等效于用于存储输入的当前二维数组
- 如何使用二维数组来计算和存储来自其他数组的值的频率
- 存储二维数组指针的方法是什么
- visual 将文件中的数据存储到C++中的二维数组中
- 如何在二维数组中存储数据并使用2个循环显示二维
- 什么是快速矩阵或二维数组,用于在C++中存储邻接矩阵
- 如何在大型二维数组中存储数据
- 如何从文本文件中读取矩阵并将其存储到二维数组中
- 存储具有不同列大小的动态分配的二维数组
- 如何在c++中按列主顺序存储二维数组中的值
- 二维数组,计算并存储6个随机连接点
- 如何在动态二维数组中存储数据,在结构体中声明,该结构体也被c++中的另一个结构体使用