C++: Can’t understand this code

typedef typename vector<Location>::iterator iterator;

This defines a new type alias iterator which maps to vector<Location>::iterator. The typedef itself isn’t actually used in this piece of code though.

unordered_map<Location, vector<Location> > edges;

This defines an std::unordered_map http://www.cplusplus.com/reference/unordered_map/unordered_map/ edges in which Location (which is the templated type) is the Key value and an std::vector of Locations is the mapped value.

it seems like Location is the key and vector is the mapped value? Is
this right?

That’s right, Location can be accessed by accessing the first member of the pair and the vector can be accessed by accessing the second member of the pair.

 inline const vector<Location>  neighbors(Location id) {
        return edges[id];
      }

inline tells the compiler that it shouldn’t treat the function as as an actual function but it should replace the code in the function body with the calling code:

Graph<int> graph;
auto result = graph.neighbors(5);

With inlining this code would translate to:

Graph<int> graph;
auto result = graph.edges[id];

Note that inline is just a hint, the compiler doesn’t actually have to listen to it.

Leave a Comment