我试图通过读取一个文本文件来创建一个有向图,其中每行有两列,第一列是尾顶点,第二列是头顶点。目前只是为了测试我的代码是否有效,我正在尝试填充图表并将其打印出来。
我在每次插入节点后打印我的图表。图形打印工作正常,直到我插入第三个节点“4”,之后第一个节点从 1 变为 0。我不知道为什么。我想知道将节点指针存储在边缘是否是个好主意。我这样做是因为我已经在“节点”向量中有节点信息,因此不想复制它。
输入测试文件:
1 2
4 5
我的数据结构是:节点:保存节点ID和布尔变量节点脏边:保存指向尾节点和头节点图的指针:保存所有节点和边的向量
输出:
Pushing :1
print called
Nodes are:
1
Pushing :2
print called
Nodes are:
1
2
Pushing :4
print called
0(0) --> 2(0) // Problem this should have been 1(0) --> 2(0)
Nodes are:
1
2
4
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
class node {
public:
node() {}
node(int _nodeId, bool dirty);
int nodeId;
bool dirty;
void operator=(node rhs);
bool operator==(node rhs);
};
class edge {
public:
edge(node *_startNode, node *_endNode): startNode(_startNode), endNode(_endNode) {}
node *startNode, *endNode;
};
node :: node(int _nodeId, bool _dirty) {
nodeId = _nodeId;
dirty = _dirty;
}
void node :: operator=(node rhs) {
this->dirty = rhs.dirty;
this->nodeId = rhs.nodeId;
}
bool node :: operator==(node rhs) {
if (this->nodeId == rhs.nodeId) {
return true;
}
return false;
}
class graph {
public:
void print();
void addEdge(node startNode, node endNode);
void addNode(node n);
void dfs(node s);
private:
vector<edge> edges;
vector<node> nodes;
};
void graph :: addNode(node n) {
// only add this node if it does not exist in the graph
if (find(nodes.begin(), nodes.end(), n) == nodes.end()) {
//print();
cout << "Pushing :"<<n.nodeId<<endl;
nodes.push_back(n);
}
print();
cout << endl;
}
void graph :: dfs(node s) {
// Search node s and mark it as dirty
}
void graph :: print() {
cout << "print called\n";
vector<edge>::iterator itr = edges.begin();
while (itr != edges.end()) {
cout << itr->startNode->nodeId << "("<< itr->startNode->dirty<<") --> ";
cout << itr->endNode->nodeId << "("<< itr->endNode->dirty<<")"<<endl;
++itr;
}
cout << "Nodes are:\n";
for (int i=0; i< nodes.size(); ++i) {
cout << nodes.at(i).nodeId << endl;
}
}
void graph :: addEdge(node startNode, node endNode) {
vector<node>::iterator itrStartNode;
itrStartNode = find(nodes.begin(), nodes.end(), startNode);
vector<node>::iterator itrEndNode;
itrEndNode = find(nodes.begin(), nodes.end(), endNode);
edge e(&(*itrStartNode), &(*itrEndNode));
edges.push_back(e);
}
int main(int argc, char *argv[]) {
graph g;
// Read the file here
ifstream file;
file.open("test.txt", ios::in);
string line;
while (getline(file, line)) {
int startNodeId, endNodeId;
istringstream is(line);
is >> startNodeId >> endNodeId;
node startNode(startNodeId, false);
node endNode(endNodeId, false);
g.addNode(startNode);
g.addNode(endNode);
g.addEdge(startNode, endNode);
}
file.close();
g.print();
return 0;
}