免责声明:我正在做作业,但这是我写的。
我正在尝试向后浏览链接列表并向前打印元素。这个snippit应该打印出来:
Chicago
ELSE
Boston
IF
2, Boston, Chicago
但是该功能最终打印/抛出这个:
Chicago
ELSE
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
Aborted
我看过其他bad_alloc问题,但似乎没有任何工作。如果我改变我的功能使e是一个顶点*它打印出来:
Chicago
ELSE
�3�����`��=��=��=��3�����p4�0=�P=�P=�(4�����>�0>�0>�x5������=�>�>��5�����P6��6��6�86������>��>��>��6�����0�`=�p=�p=�87������?� @�P@�h7�����P<�p<�p<��;�����`@��@��@�8<����� ?�P?�`?�1Seattle1�9���(:���1Yakima1�9����:�{�-1,-1!�<���!��1�:���@;�G�95,-1!h8���!p<���1h8���9�X�,-1!h8���Qh8����8�j�H9�X�-1,-1,-11,-1,-1,-1,-1!9�j�!�9���1�:����:���11,-1Q�@�!����-1,-1,-1,-1,-1,-1,-1,185,-1,142,01,142,0142,0108����9�`�1����@;�G�,142,01�>���@;�G�42,0Q�8�G��:���;� �,-1,0,1420,1420,142a�5����9����:�{�;���@;���,-1��8����9����:�{�;���@;���1�:���@;� �,0,142Q&����1095,-1,-1,-1,-1,-1,-1,-1,185,-1,142,0142,01�6
我确信这是一个简单的解决方案,但我没有看到它,也没有大约一个小时。
void Graph::printHelp(vertex e,int c){
cout << e.name << endl;
if(e.previous == NULL) {
cout << "IF" << endl;
cout << c << ", " << e.name << endl;
}
else{
cout << "ELSE" << endl;
printHelp(*e.previous,c+1);
std::cout << ", " << e.name << endl;
}
}
编辑:这是顶点结构的模式:
struct vertex{
std::string name;
bool visited;
int distance;
vertex *previous;
int district;
std::vector<adjVertex> adj;
};
EDIT2:我的代码更多是BF搜索的一部分:
for(int i=0;i<15;i++){
vertices[i].visited=false;
vertices[i].previous=NULL;
}
vector<vertex> next;
next.push_back(vertices[s]);
for(z=0;!vertices[e].visited;z++){
for(j=0;j<next[z].adj.size();j++){
if(!next[z].adj[j].v->visited){
next[z].adj[j].v->visited = true;
next[z].adj[j].v->previous = &next[z];
next.push_back(*(next[z].adj[j].v));
}
}
}
cout << vertices[s].name << endl;
printHelp(vertices[e],0);
cout << endl;
在这里我们添加Vertex方法来制作顶点:
void Graph::addVertex(string n){
bool found = false;
for(int i = 0; i < vertices.size(); i++){
if(vertices[i].name == n){
found = true;
cout<<vertices[i].name<<" found."<<endl;
}
}
if(found == false){
vertex v;
v.name = n;
vertices.push_back(v);
}
}