如何存储坐标以便与以后的坐标进行比较



这是家庭作业。我有一个在网格中移动的机器人。我需要存储他访问的每个坐标,然后检查他以前是否访问过它们。现在我正在将坐标存储在一对中,但是如何将对存储在列表/数组中,以便我可以将他以后访问的坐标与它进行比较,如果他以前没有去过那里,则可以将其添加到列表中?

这是我的代码。

#include <iostream>
#include <array>
#include <utility>
#include <list>

using namespace std;
void check (pair<int, int> foo)
{
    int points[10000];
    cout << "x " <<foo.first;
    cout << "y "<< foo.second << endl;
}
int main()
{
int numberOfLines = 0;
string strDirection;
int counter = 0;
cin >> numberOfLines;
do
{
    counter++;
    int tempStrSize = 0;
    int y = 0;
    int x = 0;
    int intDirection = 0;
    cin >> strDirection;
    tempStrSize = strDirection.size();
    char direction[tempStrSize];
    pair<int, int> foo;
    for(int i = 0; i<tempStrSize; i++)
    {
        direction[i] = strDirection.at(i); 
    }
    for (int i = 0; i < tempStrSize; i++)
    {
        if(direction[i] == 'h' || direction[i] == 'H')
        {
            if(intDirection == 3)
            {
                intDirection = 0;
            }
            else if(intDirection != 3)
            {
                intDirection++;
            }
        }
        else if(direction[i] == 'v' || direction[i] == 'V')
        {
            if(intDirection == 0)
            {
                intDirection = 3;
            }
            else if(intDirection != 0)
            {
                intDirection--;
            }
        }
        else if(direction[i] == 'f' || direction[i] == 'F')
        {
            if(intDirection == 0)
            {
                y++;
                foo = make_pair(x,y);
            }
            if(intDirection == 1)
            {
                x++;
                foo = make_pair(x,y);
            }
            if(intDirection == 2)
            {
                y--;
                foo = make_pair(x,y);
            }
            if(intDirection == 3)
            {
                x--;
                foo = make_pair(x,y);
            }
        }
        check(foo);
    }
    cout << endl;
    cout << x << " " << y << endl;
}
while(counter < numberOfLines);
return 0;
}

我会使用地图或unordered_map:

#include <unordered_map>
unordered_map<pair<int, int>,bool> visitedPoints;
bool checkVisited(pair<int, int> &coords)
{
    return visitedPoints.find(coords) != visitedPoints.end();
}
void addVisited(pair<int, int> &coords)
{
    if(!checkVisited(coords)) visitedPoints[coords] = true;
}

只是为了检查该对是否在地图中并保存访问过的点。

最新更新