1
今天早上我正在做我的C++類的分配,一個拓撲排序的實現。編譯時沒有錯誤,但根本無法運行。由於我不太熟悉指針或STL,也沒有VS調試器......我只是無法弄清楚哪裏出了問題。如果有人能指出我的錯誤,這將幫助我很多。好感謝!拓撲排序的C++實現
這裏是我的代碼:
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
typedef struct Vertex{
int index;
int indegree; // indegree of vertex v is the total num of edges like(u,v)
vector<Vertex>adjacent;
int topoNum; // topological order of this vertex.
}Vertex;
typedef struct Edge{
Vertex start;
Vertex in;
}Edge;
Vertex*InDegrees(int numVertex,int numEdge,Edge*edges) // calculate indegrees of all vertices.
{
Vertex*vertices=new Vertex[numVertex];
for(int i=0;i<numVertex;i++){ vertices[i].index=i; vertices[i].indegree=0;}
for(int i=0;i<numEdge;i++)
{
int j=edges[i].in.index;
vertices[j].indegree++;
vertices[j].adjacent.push_back(edges[i].start);
}
return vertices;
}
int*topoSort(int numVertex,int numEdge,Edge*edges)
{
edges=new Edge[numEdge];
Vertex*Vertices=new Vertex[numVertex];
Vertices=InDegrees(numVertex,numEdge,edges);
queue<Vertex>q;
for(int i=0;i<numVertex;i++)
{
if(Vertices[i].indegree==0)
q.push(Vertices[i]);
}
int count=0;
while(!q.empty()) // Ordering completed when queue is empty.
{
Vertex v=q.front(); // get the vertex whose indegree==0
q.pop();
v.topoNum=++count;
vector<Vertex>::iterator iter;
for(iter=v.adjacent.begin();iter!=v.adjacent.end();iter++)
{
Vertex w=*iter;
if(--w.indegree==0)
q.push(w);
}
}
int*topoOrder=new int[numVertex];
for(int i=0;i<numVertex;i++)
{
int j=Vertices[i].topoNum;
topoOrder[j]=-1; // initial value, in case cycle existed.
topoOrder[j]=Vertices[i].index;
}
delete[]Vertices;
delete[]edges;
return topoOrder;
}
int main()
{
int numVertex,numEdge;
cin>>numVertex>>numEdge;
Edge*Edges=new Edge[numEdge];
int indexStart,indexIn;
for(int i=0;i<numEdge;i++)
{
cin>>indexStart>>indexIn;
Edges[i].in.index=--indexIn;
Edges[i].start.index=--indexStart;
}
int*topoOrder=new int[numVertex];
topoOrder=topoSort(numVertex,numEdge,Edges);
for(int i=0;i<numVertex-1;i++)
{
if(topoOrder[i]==-1)
{
cout<<"Cycle exists, not a DAG!";
return 0;
}
cout<<topoOrder[i]<<",";
}
cout<<topoOrder[numVertex-1]<<endl;
delete[]Edges;
return 0;
}
當你運行這個程序時會發生什麼? –
爲什麼不使用向量而不是手動分配/刪除指針內存? –
undefined
@undefined:你的意思是,而不是像瘋了一樣泄露? –