I’ve been thinking about creating a class in C++ on graph theory. The idea is it’ll be a class to hold indefinite number of vertices and edges for a simple graph (at most one edge between a pair of vertices). The problem is how’d I store this indefinite number of vertices/edges in the most efficient way.
I came up with the idea of having dynamic pointer to array of vertices as a member in the class. However, it’d be inefficient, and I also encounter problem of how to determine the connection of vertices (I wouldn’t be able to determine which vertices connect with which), if I use this method. The alternative is to create a class Vertex that suppose to contain information of its connectivity. However, because of indefinite number of edges, I cannot think of other way around other than to use dynamic variables inside Vertex. It’d make my code efficiency worse with this approach.
So is there a better approach?
If you do not plan to frequently add and remove items from inside the collections, I’d use STL vectors. They’re fast for iterating through, but not terrible for inserts and removes in the middle.
If you want to add / remove anywhere frequently, I’d use STL lists. They’re slower for iterating, but insertion / removal is O(1).
You can then define your vertex and edge as something like: