【发布时间】:2011-05-27 17:41:08
【问题描述】:
我有一个队列问题。建模一个图,我正在用 C++ 做一个最短路径算法。
在我的while (!q.empty()) 中,当我返回此语句时,前面的vertex* 会发生变化。
你能找出原因吗?
int MyMatrix::searchBreadth(MyVertex* from,MyVertex* to)
{
queue<MyVertex*> q;
path=INFINITY;
from->visit();
from->setDistance(0);
q.push(from);
//here q.front()'s attributes get changed when returning from the for-loop
while(!q.empty())
{
MyVertex* v=q.front();
q.pop();
int k=v->getDistance();
vector<MyVertex> nb=getNeighbours(*v);
for(int i=0;i<nb.size();i++)
{
if(nb[i].getDistance()==INFINITY)
{
nb[i].setDistance(k+1);
q.push(&nb[i]);
}
if((nb[i].getName().compare(to->getName())==0)
&& !nb[i].isVisited())
{
//path found
int j=nb[i].getDistance();
if(j<path) path=j;
}
nb[i].visit();
}
}
return path;
}
getNeighbours() 来了
vector<MyVertex> MyMatrix::getNeighbours(MyVertex &v)
{
int index=0;
for(int l=0; l<stations.size(); l++ )
{
if(stations[l].getName().compare(v.getName())==0)index=l;
}
vector<MyVertex> out;
for(int k=0;k<matrixSize;k++)
{
if(matrix[index][k].getName().compare("null")!=0)
{
out.push_back(matrix[index][k].getTo());
}
}
return out;
}
【问题讨论】:
-
我想我不是 100% 确定我是否理解您的问题。
q.front()应该在每次迭代时更改。除非您的意思是v在for循环期间发生变化。 -
@sixlettervariables OP 表示
q.front()的属性正在改变,而不是q.front()本身。 -
@Howard:谢谢,我已经更新了答案以解决原因。
-
谢谢,我添加了 getNeighbours()
标签: c++ algorithm graph queue vertex