创建一个字符的2D矩阵的问题

Problem with creating a 2D matrix of characters

本文关键字:2D 问题 字符 一个 创建      更新时间:2023-10-16

我一直在尝试从文本文件中的数据输入中创建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输入中要求MN,但您已经将它们作为函数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;
}