我可以搜索字符向量的向量以找到特定的字符并获得其坐标



我有一个房间的地图,我将其放入字符向量的向量(vector>(中。该地图看起来像这样:

# * #
* * D
S * #

其中#是墙壁, *是路径区域,S是开始,D是末端。我不知道该地图提前是什么样子,所以我希望我的程序能够阅读任何具有与上面类似特征的地图。

因此,我希望能够搜索我的向量向量以找到S的坐标/位置,因此我知道迷宫的起点在哪里。我只能找到只有一个向量的示例(一维(。这可能与向量的向量(二维(一起做?如果是这样,我该怎么做?

这是我用来创建矩阵的代码:

vector<vector<char>> GetMap(int& M, int& N) //function to get the map of a room
{
    vector<vector<char>> matrix{}; //give a matrix
    char char_buf;
    for (int rows = 0; rows < M; rows++)
    {
        matrix.push_back(vector<char>()); //Put a new empty row in your matrix
        for (int cols = 0; cols < N; cols++)
        {
            cin >> char_buf; //Here we get a char from cin
            matrix.back().push_back(char_buf); //That you push back in your sub-vector
        }
    }
    return matrix;
}

首先,您的GetMap功能不断推回新元素。当您已经拥有可用的矩阵的大小时,这是一个很大的否(MN(。另外,确实不需要大小参数为int&类型。一个简单的int很好,在大多数情况下,更有效。

经验法则:仅对vectorstring和几乎所有类的非基础类型使用参考。

另外,您使用int&而不是const int&的事实不允许您通过RVALUES(没有名称的变量(调用该功能。例如GetMap(5, 5)

现在,最终回答您的问题。由于您已经对如何解析GetMap函数中的整个矩阵有一个想法。我真的看不到创建类似功能的问题,该函数会获得所需的字符。

具有一些增强功能的完整工作代码:

#include <iostream>
#include <vector>
using namespace std;
struct Pos{
    Pos()             : x(0), y(0) {}
    Pos(int x, int y) : x(x), y(y) {}
    int x;
    int y;
};
vector<vector<char>> GetMap(const int height, const int width) //function to get the map of a room
{
    //Create the matrix with the constructor (much more efficent than constantly push_back'ing elements)
    vector<vector<char>> matrix(height, vector<char>(width));
    //Go through every single char in the matrix
    for (int rows = 0; rows < height; rows++)
    {
        for (int cols = 0; cols < width; cols++)
        {
            cin >> matrix[rows][cols];
        }
    }
    return matrix;
}
Pos getElementPos(const vector<vector<char>>& matrix, const char toFind)
{
    int height = matrix.size();
    int width  = matrix[0].size();
    //Go through every single char in the matrix
    for (int rows = 0; rows < height; rows++)
    {
        for (int cols = 0; cols < width; cols++)
        {
           if(matrix[rows][cols] == toFind){
               return Pos(cols, rows);
           }
        }
    }
    // In the event that we couldn't find the element
    return Pos(-1, -1);
}
int main(){
    vector<vector<char>> map = GetMap(5, 5);
    Pos dPos = getElementPos(map, 'D');
    cout << "nThe coordinates of D are " << dPos.x << " and " << dPos.y << 'n';
    return 0;
}

最新更新