gpt4 book ai didi

c++ - 列表迭代器不可取消引用

转载 作者:行者123 更新时间:2023-11-30 01:44:08 26 4
gpt4 key购买 nike

我一直在为用户输入机场名称的机场开发最低成本算法,然后我运行这个算法来吐出你可以去的所有目的地,以及最低成本,包括转机航类.我使用列表迭代器从源位置迭代可到达的目的地,但仅在一次迭代后,代码就会中断,并出现一条消息告诉我迭代器不可取消引用。这是我的代码

//Finds minimum cost
void findPaths(std::string source)
{
std::list<int> Reachable;
int min = INTMAX_MAX;
int lowestIndex = -1;
bool existsInList = true;
std::stack<std::string> connectingFlights;
//Make arrays
//Initialize costs to a high value so any value will be smaller
int costs[MAX]{INTMAX_MAX};

//Initialize paths to negative one so that we know there is no location
int path[MAX]{ -1 };

//Find where the source is
int srcIndex = findOrInsert(source);

//Put the costs into the array, leaving the high number for where there is no path
for (int i = 0; i < MAX; i++)
{
costs[i] = priceEdges[srcIndex][i];
}

//Put the source index in places that have a path
for (int i = 0; i < MAX; i++)
{
if (priceEdges[srcIndex][i] == 0)
{
path[i] = -1;
}
else
{
path[i] = srcIndex;
Reachable.push_back(i);
}
}

//If the list is empty, we are done;
while (!Reachable.empty())
{
//Find the index that has the lowest value in costs
for (std::list<int>::iterator it = Reachable.begin(); *it < Reachable.size(); it)
{
if (costs[*it] < min)
{
min = costs[*it];
int lowestIndex = *it;
}

//Remove the index with the lowest value in costs
Reachable.erase(it);

//Save the previous cost to compare after a change may occur
int prevCost = costs[lowestIndex];

//Assign the value to the lowest cost it can find
costs[lowestIndex] = FindMin(costs[lowestIndex], costs[srcIndex] + priceEdges[srcIndex][lowestIndex]);

//If the price has changed
if (prevCost != costs[lowestIndex])
{
path[lowestIndex] = srcIndex;
}
existsInList = std::find(Reachable.begin(), Reachable.end(), lowestIndex) != Reachable.end();
if (!existsInList)
{
Reachable.push_back(lowestIndex);
}
}
}

最佳答案

您的 for 循环完全错误。您在未验证迭代器是否有效的情况下取消引用它,并且您正在将迭代器引用的目标值与 vector 的大小进行比较,这是没有意义的,因为它们是两个完全不同的东西。

您需要用这个替换循环:

for (std::list<int>::iterator it = Reachable.begin(); it != Reachable.end(); )

甚至这样:

std::list<int>::iterator it = Reachable.begin();
while (it != Reachable.end())

然后,为了满足循环的停止条件,您需要更改这一行:

Reachable.erase(it);

改为:

it = Reachable.erase(it);

您要从 list 中删除一个项目,这会使迭代器失效,但您永远不会更新迭代器以指向下一个项目,因此代码在尝试取消引用时会出现问题再次迭代器。 erase() 将迭代器返回到列表中被删除项目之后的下一个项目。

此外,在这一行:

int lowestIndex = *it;

您正在声明一个新的临时变量,该变量随后立即超出范围,因此永远不会被使用。您在函数的开头声明了一个先前的 lowestIndex 变量,您在初始化后永远不会为其赋值,因此它始终为 -1。您需要从分配中删除 int:

lowestIndex = *it;

关于c++ - 列表迭代器不可取消引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36732725/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com