Given an empty boost::graph g, I want to set the number of vertices in this graph and add some edges then. But from the documentation, I cannot find related functions. All examples I found defines the size of vertices in initialization (like Graph g(10) defines a graph with 10 vertices). But I don't know the size when I define the graph. I want to first define a Graph g, and set the size later.
Asked
Active
Viewed 1,570 times
2 Answers
2
You can probably try a little dirty trick like:
add_edge(0,4999,g);
remove_edge(0,4999,g);
It exploits the side-effect of add_edge for adjacency_list, namely, the fact that BGL extends the vector of vertices if necessary.

Michael Simbirsky
- 3,045
- 1
- 12
- 24
-
I've tried this and verified with `num_vertices(Graph)` and it works! – Wiredchop Jul 07 '17 at 14:52
1
The simplest approach is to call the boost::add_vertex( graph ) method for each vertex you want.
Here is a nice place to start Using C++ Boost's Graph Library
Note that you not HAVE to add the vertices one by one. If all you care about are the edges, then add_edge() will add missing vertices for you.

Community
- 1
- 1

ravenspoint
- 19,093
- 6
- 57
- 103
-
Thanks for your answer. The problem is, if I need to add 5000 vertices, I don't want to call 5000 times add_vertex(), it may be very slow. – LittleSweet Jul 11 '13 at 18:53
-
1Decide how long you can afford to spend on this task. Write some test code. Measure. If it takes too long, then ask a question with some code and some measurements. – ravenspoint Jul 11 '13 at 18:59
-
@ravenspoint I agree with LittleSweet - I've run a profiler and it seems memory allocation for the graph is taking 70% of my runtime. Is there anyway to preallocate for the number of edges that I will be adding? – David Doria Oct 19 '16 at 12:02