首页 > 解决方案 > 我可以搜索字符向量的向量以找到特定字符并获取其坐标吗?

问题描述

我有一张房间的地图,我已将其放入字符向量向量 (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;
}

标签: c++vector

解决方案


首先,您的GetMap功能不断推出新元素。当您已经拥有可用的矩阵大小时,这是一个很大的禁忌(MN)。此外,实际上不需要 size 参数是 type int&。一个简单的 int 就可以了,而且在大多数情况下,效率更高。

经验法则:仅对非基本类型(如vectorstring以及几乎所有类)使用引用。

int&此外,您使用和不使用的事实const int&不允许您通过传递右值(没有名称的变量)来调用函数。例如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;
}

推荐阅读