我试图实现使用邻接列表的Graph数据结构。要填充,我必须从文件中读取数据。该文件是一个文本文件,其中第一行包含两个数字。第一个是顶点数n,第二个是边数m。在此行之后将有m行,其中包含三个数字。前两个数字表示无向边的源和目标顶点。第三个数字(正整数)是该边缘的权重。
文件的内容如下所示:
5 7
0 1 3
0 2 4
0 3 5
1 4 10
2 5 20
3 4 6
4 5 4
但由于某种原因,我到目前为止编写的代码使程序崩溃。并且编译器没有给出任何关于原因的提示。 我真的很感激一些建议。我已经阅读了很多关于指针,C ++中的引用,但仍然发现它们令人困惑。因此,更好地理解它们的良好资源确实会有所帮助。
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
using namespace std;
struct Vertex
{
unsigned value;
vector<Vertex*> adjList;
vector<unsigned> weights;
};
class Graph
{
private:
unsigned vertex_count, edge_count;
vector<Vertex*> vertices;
public:
Graph(string fileName)
{
ifstream myFile(fileName);
if (myFile.is_open())
{
// Processing the first line of the file
string aLine;
getline(myFile, aLine);
stringstream aString(aLine);
aString >> vertex_count;
aString >> edge_count;
// Processing the rest of the file
unsigned vert1, vert2, weight;
while (getline(myFile, aLine))
{
aString= stringstream(aLine);
aString >> vert1;
aString >> vert2;
aString >> weight;
addRelation(vert1, vert2, weight);
}
}
else
cout << "Unable to open file.";
}
~Graph()
{
for (unsigned i = 0; i < vertices.size(); i++)
delete vertices[i];
}
void addVertex(unsigned val)
{
Vertex* newVertex = new Vertex;
newVertex->value = val;
vertices.push_back(newVertex);
}
Vertex* findVertex(unsigned val)
{
for (unsigned i = 0; i < vertices.size(); i++)
if (vertices[i]->value = val)
return vertices[i];
return nullptr;
}
void addRelation(unsigned vert1, unsigned vert2, unsigned weight)
{
Vertex* vertex1 = findVertex(vert1);
if (vertex1 == nullptr) {
addVertex(vert1);
vertex1 = findVertex(vert1);
}
Vertex* vertex2 = findVertex(vert2);
if (vertex2 == nullptr) {
addVertex(vert2);
vertex2 = findVertex(vert2);
}
vertex1->adjList.push_back(vertex2);
vertex1->weights.push_back(weight);
vertex2->adjList.push_back(vertex1);
vertex2->weights.push_back(weight);
}
};
int main()
{
Graph myG("graph.txt");
return 0;
}
答案 0 :(得分:1)
你的几个if语句使用=而不是==。如果在编译器中启用警告,则会发现类似:
test.cpp:69:36: warning: using the result of an assignment as a condition without parentheses [-Wparentheses]
if (vertices[i]->value = val)
~~~~~~~~~~~~~~~~~~~^~~~~
test.cpp:69:36: note: place parentheses around the assignment to silence this warning
if (vertices[i]->value = val)
^
( )
test.cpp:69:36: note: use '==' to turn this assignment into an equality comparison
if (vertices[i]->value = val)
答案 1 :(得分:0)
你的if表达式指的不是比较。
Vertex* findVertex(unsigned val)
{
for (unsigned i = 0; i < vertices.size(); i++)
if (vertices[i]->value = val) // WHOOPS!
return vertices[i];
return nullptr;
}
更改为:
Vertex* findVertex(unsigned val)
{
for (unsigned i = 0; i < vertices.size(); i++)
if (vertices[i]->value == val) // FIXED
return vertices[i];
return nullptr;
}