I am working on the shortest path problem, this means that I have to create a data type or class to simulate my map. To do this currently I am using a map<string, map<string, int>> where the first string is the name of the node (call it node A), and the second parameter is a map of the nodes that A connects with to their distances to A.
While this works decently, I find it a rather cumbersome way to deal with my nodes, and creating the map is more time consuming than the actual algorithm. Can anyone suggest any decent ways of representing something like this elegantly in a C++ data structure?
Sorry, to clarify. Firstly, both the syntax is manageable but if someone could suggest something more elegant it’d be welcome, iterating over the map is extremely frustrating as I must also iterate over “sub maps” within each pair on the larger map. Secondly, I measured the time to create a map of 10 nodes and compared it to the time it took for the actual algorithm to run, it took longer to create then run.
One very simple approach is… a table.
This can be implemented rather trivially, you then just need to devise a way to represent the absence of connection, which can be done by using a sentinel value.
Second, the way you represent nodes is not very adequate. Strings are heavyweight beasts. I would suggest to create a mapping from the real names to simple numbers, and then only use numbers in the table.
For example, you could use such an approach:
Of course, it would be much simpler if you encoded the nodes straight away and only dealt with integrals (this would remove all this string->unsigned conversion from within the class).
Also note that I created a class for a directed graph, if the graph is not directed, you have to chose between: