1

我有队列问题。建模一个图,我正在用 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;
}
4

1 回答 1

3

您的问题很微妙,但与q.push(&nb[i]). 您正在做的是添加指向向量中某个位置的指针,这在概念上与添加指向MyVertex对象的指针不同。邻居向量包含MyVertex“按值”的对象(如果这有助于您理解问题)。

查看nb内存可能会有所帮助:

        0         1                   I
nb [MyVertex0|MyVertex1|   ...   |MyVertexI]
             +---------+
                  | (Notice it is NOT pointing to MyVertex1!)
&nb[1]------------+

当您推送时,&nb[1]您正在推送地址nb + (1 * sizeof(MyVertex))nb在堆栈上声明,因此该地址将位于堆栈上的某个位置。

因此,当您的for-loop 回来时,nb会刷新(可以这么说)并添加新数据。但是,您的队列q包含nb不再有效的地址!

简单地说:您的队列引用的是向量中的 LOCATION,而不是向量中的 DATA

如果您想保持方法不变,这意味着getNeighbors需要更改以返回MyVertex*.


您应该简单地编辑BreadthFirstSearch以获取两个MyVertex&,而不是指针。然后你会q变成 a queue<MyVertex>, vto MyVertex,最后你应该变成q.push(&nb[i])just q.push(nb[i])

于 2011-05-27T17:50:41.760 回答