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

- 616
- 6
- 19
-
Take a look at this nice blog post where it says how can we create a C++ graph using STL: http://theunixshell.blogspot.in/2014/02/creating-graph-using-stls-in-c.html – Vijay Apr 18 '14 at 19:22
1 Answers
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
. I'll talk about the first difference first (that is, list<vertex>
vs 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)
Add Edge: 1 vs log V
Check Adjacency: (degree of vertex checked) vs log V
Iterating through Neighbours of a vertex: (degree of vertex checked) vs (log V + degree of vertex checked)
... 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. (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, i.e. 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. However lookup is O(1) for vector and O(log N) for map. 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?