Reputation: 13
I am new to boost library. Is there any way to find all the child nodes of a graph using boost. Or any document which I can refer to for implementing this would be helpful. I thought of using Out_Edge Iterator because no out edge implies child node.
Upvotes: 1
Views: 1538
Reputation: 392843
On first reading I understood your question literally. Only on second reading I suspected you actually meant to look for leaf nodes.
The question makes sense if you have a given node (say, vertex #5) and want to list the nodes that are reachable using 1 arc (edge).
Given a graph:
boost::adjacency_list<> g(10);
You get the vertex-descriptors of all the children of vertex 5:
for (auto vd : boost::make_iterator_range(adjacent_vertices(5, g)))
{
std::cout << "vertex " << vd << " is an out-edge of vertex 5\n";
}
To make things a little bit more interesting, let's generate a random graph:
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/random.hpp>
#include <iostream>
#include <random>
int main() {
boost::adjacency_list<> g;
std::mt19937 rng { 42 };
generate_random_graph(g, 10, 20, rng);
for (auto vd : boost::make_iterator_range(adjacent_vertices(5, g)))
{
std::cout << "vertex " << vd << " is an out-edge of vertex 5\n";
}
}
Prints
vertex 1 is an out-edge of vertex 5
vertex 6 is an out-edge of vertex 5
And the graph is visualized as:
The number of edges connecting a vertex is called its degree. The number of outgoing edges can be queried with out_degree
:
for (auto vd : boost::make_iterator_range(vertices(g)))
std::cout << "vertex #" << vd << " has out_degree: " << out_degree(vd, g) << "\n";
You'll see that this means that vertices #1 and #2 are leaf nodes.
Visualizing leaf nodes: Live On Coliru
Upvotes: 2