创建一个字符的2D矩阵的问题
Problem with creating a 2D matrix of characters
我一直在尝试从文本文件中的数据输入中创建2D矩阵的多种方法。但是,我尝试的各种方式都会不断遇到错误。下面代码中的方法是错误最小的方法,但我仍然在返回对象上遇到一个错误,说我正在使用非初始化的内存"矩阵"。抱歉,如果这是一个简单的解决方案,我对C 非常新。
我以前尝试过向量的向量,但遇到了错误的尺寸的问题。如果有人可以从文本文件中创建字符矩阵的更好方法,请告诉我!
char** GetMap(int& M, int& N) //function to get the map of a room
{
int M = 0; // initializing rows variable
int N = 0; // initializing columns variable
char** matrix; //give a matrix
cin >> M >> N;
for (int rows = 0; rows < M; rows++)
{
for (int cols = 0; cols < N; cols++)
{
cin >> matrix[rows][cols];
}
}
return matrix;
}
首先让我告诉你,您在std::cin
输入中要求M
和N
,但您已经将它们作为函数char** GetMap(int& M, int& N)
的参数。
现在,您可能需要需要在您的情况下使用std::vector
。实际上,您想使用两个变量M和N初始化char** matrix
,在适当的C 中不允许。
解决此问题的好方法是使用std::vector<std::vector<char>> matrix
而不是char** matrix
。这是一个解决您期望的解决方案
std::vector<std::vector<char>> GetMap(int& M, int& N) //function to get the map of a room
{
std::vector<std::vector<char>> matrix{}; //give a matrix
char char_buf;
for (int rows = 0; rows < M; rows++)
{
matrix.push_back(std::vector<char>()); //Put a new empty row in your matrix
for (int cols = 0; cols < N; cols++)
{
std::cin >> char_buf; //Here you get a char from std::cin
matrix.back().push_back(char_buf); //That you push back in your sub-vector
}
}
return matrix;
}
相关文章:
- 这是使用回溯的 nqueen 问题,但我使用了动态 2d 数组,我的程序编译良好,但不返回任何输出
- 在 2D 矢量中获取多个输入时出现问题
- 超级对撞机2D阵列:生成嵌套:包装/尺寸问题
- 关于骰子概率和 2D 数组的问题
- 指向结构的指针的 2D 数组.内存访问问题
- 如何解决在使用动态 2D 数组进行矩阵乘法的 MPI 进行并行编程时的问题
- 2D旋转问题C Directx
- 创建一个字符的2D矩阵的问题
- 无法解决动态初始化 2D 数组的问题
- 双打分类/编辑问题的2D向量
- 绘制非常大的 2D 图形时出现问题
- If/Else 语句在 2D 数组中移动时出现问题
- 递归问题(2D正交)
- 我的代码正在制作 2D 数组元素的重复副本.代码中有什么问题?
- C++类和函数的问题-打印2D数组的函数
- 简单的2D应用程序,在使用glutBitmapCharacter时遇到问题
- 相同大小的2D和1D阵列之间的内存或执行问题
- 输入和输出的2D字符数组问题
- 将2D数组写入另一个C++时出现问题
- 输入到 2D 数组 - C++(第一行/列元素的问题)