无法进入 while 循环这与使用无序地图有关吗?

问题描述

我正在尝试进行编码挑战,我们必须缩短和最小化方向说明。在实现 while 循环之前,我正在使用无序映射。其余代码按预期工作,但无法到达 while 循环,因此我无法输出适当的值。

std::vector<std::string> dirReduc(std::vector <std::string>& arr)
{
    enum Direction
    {
        norTH = 1,SOUTH = -1,EAST = 1,WEST = -1
    };
    int x=0,y=0;
    std::unordered_map<std::string,Direction> uMapDir = { {"north",norTH},{"norTH",{"South",SOUTH},{"SOUTH",{"East",EAST},{"EAST",{"West",WEST},{"WEST",WEST} };
    for (std::vector<std::string> ::const_iterator i =arr.begin(); i!=arr.end() ; i ++)
    {
        if ((*i=="north")||(*i == "norTH")||(*i=="South")|| (*i == "SOUTH"))
        {
            y += uMapDir[*i];
        }
        else
        {
            x += uMapDir[*i];
        }
    }
    std::vector<std::string> outPutArr;
    while ((x!=0)&&(y!=0))
    {
        if (x<0)
        {
            x++;
            outPutArr.push_back("WEST");
        }
        else
        {
            x--;
            outPutArr.push_back("EAST");
        }

        if (y < 0)
        {
            y++;
            outPutArr.push_back("SOUTH");
        }
        else
        {
            y--;
            outPutArr.push_back("norTH");
        }
    }
    return outPutArr;
}

解决方法

您的问题是您试图在同一个循环中同时执行 xy。这意味着您必须在每个循环中push_back 向东或向西 AND push_back 向南或向北。但这没有任何意义。如果您没有相同的数量怎么办?

相反,您应该使用两个循环:

while (x)
{
    if (x<0)
    {
        x++;
        outPutArr.push_back("WEST");
    }
    else
    {
        x--;
        outPutArr.push_back("EAST");
    }
}

while(y) {
    if (y < 0)
    {
        y++;
        outPutArr.push_back("SOUTH");
    }
    else
    {
        y--;
        outPutArr.push_back("NORTH");
    }
}