首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么这个循环是没完没了的?

为什么这个循环是没完没了的?
EN

Stack Overflow用户
提问于 2020-05-09 17:13:32
回答 1查看 72关注 0票数 0

嗨,伙计们!

我想切换到UE4,现在正在尝试重复通过路点找路的功能,它在Unity中工作得很好,但在C ++中有问题。这个函数产生了一个无限循环,据我所知,openList不能为空。我的c ++知识不足以解决这个问题。我将很高兴得到任何帮助!

代码语言:javascript
复制
TArray<FVector> UWaypointsPathfinding::GetPath(UWaypoint* startNode, UWaypoint* goalNode)
{
    UWaypoint* beginNode = startNode;
    set<UWaypoint*> openList;
    vector<UWaypoint*> closedList;

    openList.insert(startNode);
    startNode->previous = nullptr;
    startNode->distance = 0;


    while (!openList.empty())
    {
        startNode = *openList.begin();
        openList.erase(openList.begin());


        float dist = startNode->distance;
        closedList.push_back(startNode);
        if(startNode == goalNode) break;

        int l = startNode->nearest.Num();
        for (int i = 0; i < l; i++)
        {
            UWaypoint* node = startNode->nearest[i]->FindComponentByClass<UWaypoint>();
            if(find(closedList.begin(),closedList.end(),node) != closedList.end() || openList.find(node) != openList.end())
                continue;

            node->previous = startNode;
            node->distance = dist + FVector::Dist(node->GetOwner()->GetActorLocation(), startNode->GetOwner()->GetActorLocation());
            node->distance += FVector::Dist(node->GetOwner()->GetActorLocation(), goalNode->GetOwner()->GetActorLocation());

            openList.insert(startNode);
        }


    }

    // create path...

    return TArray<FVector>();
}

据推测,问题出在这篇文章中

代码语言:javascript
复制
if(startNode == goalNode) break;

int l = startNode->nearest.Num();
for (int i = 0; i < l; i++)
{
   UWaypoint* node = startNode->nearest[i]->FindComponentByClass<UWaypoint>();
   if(find(closedList.begin(),closedList.end(),node) != closedList.end() || openList.find(node) != openList.end())
                        continue;

    node->previous = startNode;
    node->distance = dist + FVector::Dist(node->GetOwner()->GetActorLocation(), startNode->GetOwner()->GetActorLocation());
    node->distance += FVector::Dist(node->GetOwner()->GetActorLocation(), goalNode->GetOwner()->GetActorLocation());

    openList.insert(startNode);
}
EN

回答 1

Stack Overflow用户

发布于 2020-05-15 23:55:49

逻辑很奇怪,所以这可能是一个错误的类型。在开始处将startNode插入到openList,然后在循环中擦除它并再次插入。因此,openList将始终具有单个成员startNode,并且所有周期都是相同的。也许您的意思是在循环的最后一行使用openList.insert(node);而不是openList.insert(startNode);

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61694338

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档