Search code examples
c++graph-algorithma-star

C++: Can't understand this code


Here is the website: link.

This is the part that I don't understand:

template<typename L>
struct Graph {
  typedef L Location;
  typedef typename vector<Location>::iterator iterator;
  unordered_map<Location, vector<Location> > edges;

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

What I don't understand are these lines:

typedef typename vector<Location>::iterator iterator;
      unordered_map<Location, vector<Location> > edges;

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

The first line is what I'm most confused about, what does

vector<Location>::iterator iterator

do? Is it a function? A type? What does the :: do in this line of code?

For the second line, I've searched what unordered_maps are and it seems like Location is the key and vector is the mapped value? Is this right?

Regarding the third and fourth line, inline doesn't have to be there, right? I looked at the wikipedia page but it's too complicated for me to understand right now. Other than the inline, what the heck does the code do? What does neighbors(Location id) do? I think it's the parameter of neighbors but then what is edges[id]? Does it return the mapped value of the key id from the unordered_map edges?

Sorry if this is all wrong, I don't know many algorithms, almost none, in fact and now I'm trying to learn A* for my PAC-MAN game so there's a big knowledge gap, I think.


Solution

  • 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.