我建议使用Lemon,参见教程: http: //lemon.cs.elte.hu/pub/tutorial/a00011.html
一般来说,您将结构(图表)和数据分开。因此,如果是柠檬,您将阅读每一行,将其分成 4 个字段(分隔符是空格)。在读取文件期间,您还应该维护哈希或映射(例如 std::unordered_map)以快速查找图中已经存在的目的地(或使用图形 API 来查找它们,但这会更慢)。
所以:
ListDigraph g;
ListDigraph::NodeMap<std::string> gDestinations(g);
ListDigraph::ArcMap<int> gCosts(g);
ListDigraph::ArcMap<int> gDistances(g);
std::unordered_map<std::string, ListDigraph::Node> destinations;
然后对于每一行:
//first read the line, split it be whitespace into 4 fields, e.g. into these
std::string destFrom, destTo;
int distance, cost;
//first the structure
auto itFrom = destinations.insert(destFrom, g.addNode()).first; //dest is the first or second field in your file
auto itTo = destinations.insert(destTo, g.addNode()).first; //dest is the first or second field in your file
ListDigraph::Arc route = g.addArc(*itFrom, *itTo);
//then the data
gDestinations[*itFrom] = destFrom; //well this could be done once if the place exists already, this s for brevity
gDestinations[*itTo] = destTo; //dtto
gDistances[route] = distance; //distance is the third field
gCosts[route] = cost; //cost is the fourth field
就是这样。请参阅教程和 Lemon 文档如何使用图形算法和操作图形等。