C++:无法理解这段代码

C++: Can't understand this code

这是网站:link

这是我不明白的部分:

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];
  }
};

我不明白的是这些行:

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

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

第一行是我最困惑的地方,

vector<Location>::iterator iterator

做什么?它是一个函数吗?一种? :: 在这行代码中做了什么?

对于第二行,我搜索了 unordered_maps 是什么,Location 似乎是键,vector 是映射值?这样对吗?

关于第三行和第四行,inline 不一定要有,对吧?我查看了维基百科页面,但它太复杂了,我现在无法理解。除了内联,代码到底做了什么? neighbors(Location id) 做什么?我认为这是邻居的参数,那么 edges[id] 是什么?它 return 是来自 unordered_map 边的密钥 ID 的映射值吗?

抱歉,如果这一切都错了,我不知道很多算法,几乎 none,事实上,现在我正在尝试为我的 PAC-MAN 游戏学习 A*,所以有很多知识差距,我想。

typedef typename vector<Location>::iterator iterator;

在图形模板中定义类型别名。它具有以下一般形式:

typedef X Y;

这使得 Y 成为类型 X 的别名。在这种情况下,X 是

typename vector<Location>::iterator

其形式为

typename A::B

表示classA中的类型B。在这种情况下需要typename关键字,因为vector<Location>依赖于模板参数。

最终结果是Graph<L>中的类型iteratorvector<L>中类型iterator的别名。

typedef typename vector<Location>::iterator iterator;

这定义了一个映射到 vector<Location>::iterator 的新类型别名 iterator。 typedef 本身并没有实际用在这段代码中。

unordered_map<Location, vector<Location> > edges;

这定义了一个 std::unordered_map http://www.cplusplus.com/reference/unordered_map/unordered_map/ edges 其中 Location (这是模板化类型)是键值和 std::vector Locations 是映射值。

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

没错,Location可以通过访问pair的first成员来访问,vector可以通过访问pair的second成员来访问。

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

inline 告诉编译器它不应该把这个函数当作一个实际的函数,而是应该用调用代码替换函数体中的代码:

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

通过内联,此代码将转换为:

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

请注意inline只是一个提示,编译器实际上不必听它。