简体   繁体   English

使用stl在C ++中实现Graph的比较

[英]Comparison of Graph implementation in C++ using stl

To implement a Graph we can use vector of lists std::vector<std::list<vertex>> but i have seen somewhere if use maps like this std::map<vertex, std::set<vertex>> then we can do better. 要实现图,我们可以使用列表std::vector<std::list<vertex>>但是我看到某个地方是否使用了像std::map<vertex, std::set<vertex>>这样的std::map<vertex, std::set<vertex>>那么我们可以做得更好。 Can anybody please figure it out how this is better option than first one in terms of memory or speed whatever in which it is better? 任何人都可以找出在内存或速度方面哪个比第一个更好的选择吗?

There are two differences to note here. 这里有两个区别要注意。

std::vector<std::list<vertex>> is what is known as an "adjacency list", and std::map<vertex, std::set<vertex>> is known as a an "adjacency set", with the added difference that there is hashing of the vertex array index using a map instead of a vector . std::vector<std::list<vertex>>被称为“邻接列表”, std::map<vertex, std::set<vertex>>被称为“邻接集”,增加的区别是使用map而不是vector来散布顶点数组索引。 I'll talk about the first difference first (that is, list<vertex> vs set<vertex> ). 我将首先讨论第一个区别(即list<vertex>set<vertex> )。

The first implementation is basically an array of linked lists, where each linked list gives all the vertices adjacent a vertex. 第一个实现基本上是一个链表列表,其中每个链表给出了一个顶点附近的所有顶点。 The second implementation is an ordered map mapping each vertex to a set of adjacent vertices. 第二种实现是将每个顶点映射到一组相邻顶点的有序映射。

Comparison of Adjacency List vs Adjacency Set order of growth: 邻接列表与邻接集的增长顺序比较:

Space: (E + V) vs (E + V) 空格:(E + V)与(E + V)

Add Edge: 1 vs log V 加边:1 vs对数V

Check Adjacency: (degree of vertex checked) vs log V 检查邻接度:(检查的顶点度)与对数V

Iterating through Neighbours of a vertex: (degree of vertex checked) vs (log V + degree of vertex checked) 遍历顶点的邻居:(检查的顶点度)vs(log V +检查的顶点度)

... where E is the number of edges and V the number of vertices, and degree of a vertex is the number of edges connected to it. ...,其中E是边的数量,V是顶点的数量,顶点的度是与其连接的边的数量。 (I'm using the language of an undirected graph but you can reason similarly for directed graphs). (我使用的是无向图的语言,但是您可以类似地对有向图进行推理)。 So if you have a very dense graph (each vertex has lots of edges, ie high degree) then you want to use adjacency sets. 因此,如果您有一个非常密集的图(每个顶点都有很多边,即高度),那么您想使用邻接集。

Regarding the use of map vs vector: insert and erase are O(N) for vector and O(log N) for map. 关于地图与向量的使用:向量的插入和擦除分别为O(N)和地图的O(log N)。 However lookup is O(1) for vector and O(log N) for map. 但是,向量查找为O(1),地图查找为O(log N)。 Depending on your purposes you might use one over the other. 根据您的目的,您可以在另一个上使用一个。 Though you should note that there are cache optimizations and such when you use a contiguous memory space (as vector does). 尽管您应该注意,在使用连续内存空间时(例如向量),存在缓存优化等功能。 I don't know much about that however, but there are other answers that mention it: vector or map, which one to use? 我对此了解不多,但是还有其他答案提到它: 矢量或地图,要使用哪个?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM