I am currently writing a console program in C++ that builds a network/graph of nodes and arcs that connect to eachother using unordered maps. The purpose of the application is to demonstrate the “most efficient” way of processing commands and retrieving information from the network/graph. I’ve attached [a diagram of a similar example].(https://i.sstatic.net/51FY0RHO.png).
Below is my BuildNetwork()
method in my Network.cpp
file as well as my Graph.cpp
, Node.cpp
, and Arc.cpp
classes so you can get an idea of how my network is built:
bool Navigation::BuildNetwork(const std::string& fileNamePlaces, const std::string& fileNameLinks)
{
std::ifstream finPlaces(fileNamePlaces), finLinks(fileNameLinks);
if (!finPlaces || !finLinks)
return false;
std::string line;
// Parse Places
while (getline(finPlaces, line)) {
std::istringstream iss(line);
std::string name, idStr, latitudeStr, longitudeStr;
if (getline(iss, name, ',') && getline(iss, idStr, ',') && getline(iss, latitudeStr, ',') && getline(iss, longitudeStr)) {
int id = std::stoi(idStr);
double latitude = std::stod(latitudeStr), longitude = std::stod(longitudeStr);
Node node(id, name, latitude, longitude);
networkGraph.addNode(node);
}
}
// Parse Links
while (getline(finLinks, line)) {
std::istringstream iss(line);
std::string startIdStr, endIdStr, modeStr;
if (getline(iss, startIdStr, ',') && getline(iss, endIdStr, ',') && getline(iss, modeStr)) {
int startNodeId = std::stoi(startIdStr), endNodeId = std::stoi(endIdStr);
TransportMode mode = parseTransportMode(modeStr);
Arc arc(startNodeId, endNodeId, mode);
networkGraph.addArc(startNodeId, arc);
}
}
return true;
}
// Helper function to parse string to TransportMode
TransportMode Navigation::parseTransportMode(const std::string& modeStr) {
static const std::unordered_map<std::string, TransportMode> modeMap = {
{"Ship", TransportMode::Ship}, {"Rail", TransportMode::Rail},
{"Bus", TransportMode::Bus}, {"Car", TransportMode::Car},
{"Bike", TransportMode::Bike}, {"Foot", TransportMode::Foot}
};
auto it = modeMap.find(modeStr);
if (it != modeMap.end())
return it->second;
return TransportMode::Foot; // Default or error case
}
#include "Graph.h"
Graph::Graph() {}
Graph::~Graph() {}
void Graph::addNode(const Node& node) {
nodes[node.getId()] = node;
}
void Graph::addArc(int startNodeID, const Arc& arc) {
if (nodeExists(startNodeID) && nodeExists(arc.getEndNodeID())) {
if (adjacencyList.find(startNodeID) == adjacencyList.end()) {
adjacencyList[startNodeID] = std::vector<Arc>(); // Initialize if not already
}
adjacencyList[startNodeID].push_back(arc);
}
}
Node& Graph::getNode(int nodeId) {
return nodes.at(nodeId);
}
const Node& Graph::getNode(int nodeId) const {
return nodes.at(nodeId);
}
const std::vector<Arc>& Graph::getArcs(int nodeId) const {
return adjacencyList.at(nodeId);
}
bool Graph::nodeExists(int nodeId) const {
return nodes.find(nodeId) != nodes.end();
}
bool Graph::arcExists(int startNodeID, int endNodeID) const {
auto it = adjacencyList.find(startNodeID);
if (it != adjacencyList.end()) {
return std::any_of(it->second.begin(), it->second.end(), [endNodeID](const Arc& arc) {
return arc.getEndNodeID() == endNodeID;
});
}
return false;
}
const std::unordered_map<int, Node> Graph::getAllNodes() const {
return nodes;
}
#include "Node.h"
Node::Node(int id, const std::string& name, double latitude, double longitude)
: id(id), name(name)
{
Utility::LLtoUTM(latitude, longitude, y, x);
}
//Setting "getters" as const as they're not changing once set
int Node::getId() const
{
return id;
}
std::string Node::getName() const
{
return name;
}
double Node::getX() const
{
return x;
}
double Node::getY() const
{
return y;
}
#include "Arc.h"
Arc::Arc(int startNodeID, int endNodeID, TransportMode transportMode, double distance)
: startNodeID(startNodeID), endNodeID(endNodeID), transportMode(transportMode), distance(distance) {}
int Arc::getStartNodeID() const {
return startNodeID;
}
int Arc::getEndNodeID() const {
return endNodeID;
}
TransportMode Arc::getTransportMode() const {
return transportMode;
}
double Arc::getDistance() const {
return distance;
}
void Arc::setDistance(double dist) {
distance = dist;
}
As you can see, it utilises Unordered Maps to store the nodes and arcs. I have already implemented a method to calculate the furthest distance between two nodes in Network.cpp
. Bare in mind that this works flawlessly:
bool Navigation::maxDist(const std::string& params) {
double maxDistance = 0.0;
std::string farthestNodes;
const auto& nodes = networkGraph.getAllNodes(); // Ensure this returns a reference to the map
for (auto it1 = nodes.begin(); it1 != nodes.end(); ++it1) {
for (auto it2 = std::next(it1); it2 != nodes.end(); ++it2) {
// Calculate Euclidean distance between nodes in meters, then convert to kilometers
double dx = it2->second.getX() - it1->second.getX();
double dy = it2->second.getY() - it1->second.getY();
double squaredDistance = dx * dx + dy * dy;
if (squaredDistance > maxDistance) {
maxDistance = squaredDistance;
farthestNodes = it1->second.getName() + " to " + it2->second.getName();
}
}
}
maxDistance = sqrt(maxDistance) / 1000.0; // Convert from meters to kilometers
std::cout << "Max Distance: " << maxDistance << " km between " << farthestNodes << std::endl;
return true;
}
The issue, however, is when I try to implement a method to calculate which Node has the most connecting arcs:
bool Navigation::maxLink(const std::string& params)
{
double maxDistance = 0.0;
std::string longestLinkDescription;
Node startNode, endNode;
// Iterate over all nodes to access their adjacency lists
for (const auto& nodePair : networkGraph.getAllNodes()) {
int nodeId = nodePair.first;
const auto& arcs = networkGraph.getArcs(nodeId);
// Check each arc for this node
for (const auto& arc : arcs) {
// Make sure the end node exists to avoid out of bounds
if (!networkGraph.nodeExists(arc.getEndNodeID())) {
continue; // Skip this arc if the end node doesn't exist
}
Node start = networkGraph.getNode(nodeId);
Node end = networkGraph.getNode(arc.getEndNodeID());
// Calculate distance using the coordinates stored in nodes
double distance = Utility::arcLength(start.getY(), start.getX(), end.getY(), end.getX());
// Check if this is the longest arc found so far
if (distance > maxDistance) {
maxDistance = distance;
startNode = start;
endNode = end;
longestLinkDescription = start.getName() + " to " + end.getName();
}
}
}
// Output the longest link found and its distance
if (longestLinkDescription.empty()) {
std::cout << "No valid links found." << std::endl;
return false;
}
else {
std::cout << "Longest Link: " << longestLinkDescription << " - " << std::fixed << std::setprecision(3) << maxDistance << " km" << std::endl;
return true;
}
}
When I compile and run the program, it comes up with this error:
Unhandled exception at 0x00007FF924A2AB89 in Network.exe: Microsoft C++ exception: std::out_of_range at memory location 0x0000008FF973E380.
This confuses me, as I have already tested that every single one of the nodes and arcs have been built and initialised through debugging earlier in the program, so surely there should not be any out-of-range memory locations. This makes me think that it is not an issue with the building of the network itself, but the way in which the method runs through the unordered maps. As it doesn’t tell me specifically what is wrong with it, I’m really unsure on how to solve this. I’m relatively unexperienced with using unordered maps but I have been told it’s an efficient way to make a network like this. How do I solve the error I am seeing?