Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

print or iterate over the vertices with vertex_descriptor boost graph

Building a boost graph where edges area added (below) and v1 is defined as

gm->create_edge(v1,v2,1); 
boost::graph_traits<Graph>::vertex_descriptor v1 = gm-> create_vertex("one",1,1);

How do print or enumerate the vertices using?:

boost::graph_traits<Graph>::vertex_descriptor vd;

This allows me to print vertex id:

Graph::vertex_iterator v, vend, vnext; 
for (boost::tie(v, vend) = vertices(gm->g); v != vend; ++v)
    std::cout << gm->g[*v].id << ", "  << gm->g[*v].color << ", ";

I have a function for the degree of the node, it takes a vertex descriptor, so, how do I pass that?

gm->degree( takes vertex_descriptor )?

This links is close.

like image 387
sAguinaga Avatar asked Mar 07 '23 19:03

sAguinaga


1 Answers

vertices(g) returns an iterator pair. Indirecting the iterator gives the descriptor. In your own example v is vertex_iterator so *v is vertex_descriptor.

Lets use Boost's degree function - which also takes a descriptor:

Live On Coliru

#include <boost/graph/adjacency_list.hpp>

namespace MyProgram {
    using namespace boost;
    struct VertexProps { int id; default_color_type color; };

    using Graph = adjacency_list<vecS, vecS, directedS, VertexProps>;

    Graph make_sample_graph();
}

#include <iostream>

int main() {
    using MyProgram::Graph;
    Graph g = MyProgram::make_sample_graph();

    Graph::vertex_iterator v, vend;
    for (boost::tie(v, vend) = vertices(g); v != vend; ++v) {
        std::cout << "Vertex descriptor #" << *v 
             << " degree:" << degree(*v, g)
             << " id:"     << g[*v].id
             << " color:"  << g[*v].color
             << "\n";
    }
}

I'd prefer to use ranged-for though:

Live On Coliru

for (auto vd : boost::make_iterator_range(vertices(g))) {
    std::cout << "Vertex descriptor #" << vd 
         << " degree:" << degree(vd, g)
         << " id:"     << g[vd].id
         << " color:"  << g[vd].color
         << "\n";
}

For completeness with make_sample_graph():

namespace MyProgram {
    Graph make_sample_graph() {
        Graph g(10);
        for (auto vd : boost::make_iterator_range(vertices(g)))
            g[vd] = { int(vd)*100, {} };

        add_edge(1,2,g);
        add_edge(2,3,g);
        add_edge(4,5,g);
        add_edge(4,6,g);
        add_edge(6,7,g);

        return g;
    }
}

Prints:

Vertex descriptor #0 degree:0 id:0 color:0
Vertex descriptor #1 degree:1 id:100 color:0
Vertex descriptor #2 degree:2 id:200 color:0
Vertex descriptor #3 degree:1 id:300 color:0
Vertex descriptor #4 degree:2 id:400 color:0
Vertex descriptor #5 degree:1 id:500 color:0
Vertex descriptor #6 degree:2 id:600 color:0
Vertex descriptor #7 degree:1 id:700 color:0
Vertex descriptor #8 degree:0 id:800 color:0
Vertex descriptor #9 degree:0 id:900 color:0
like image 155
sehe Avatar answered Apr 08 '23 04:04

sehe