简体   繁体   中英

C++ Adjacency List Representation of Graphs

What is an efficient way to implement Adjacency List Representation of Graph in C++?

  1. <\/li>
  2. <\/li>
  3. <\/li>
  4. <\/li><\/ol>

    In my opinion, it should be option 3 or 4, but I could not find any cons in using that... Are there any?

What is an efficient way to implement Adjacency List Representation of Graph in C++

Many typical graph problems apply to a given static graph that will need to be represented once whereafter the given representation can be re-used whilst solving the related problem. In this case, std::unordered_map<int, std::vector<int>> is an appropriate structure; where the value for a given key in the unordered map represents the (single-/bi-directional) connected vertices for a given vertex. There should be no reason to use the ordered std::map over the amortized constant-time lookup container std::unordered_map .

The associative containers std::unordered_map and std::unordered_set are quick for lookup (which you want here), but can have performance implications if they need to mutate often (eg for a dynamic graph problem). As always, profiling and measuring runtime and memory to find bottlenecks for you actual problem implementation is key if you are implementing a highperf computation program.

This is to especially address your fourth option.

In that book they use Java and work with the Bag data structure, which is an unordered collection of objects, with the possibility for duplicates.

As he says, one needs to measure for one's application to decide.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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