Travis Su
Travis Su

Reputation: 709

How to set the same edge weight in a graph using a loop using Boost Graph Library?

As the Boost documentation might include this but it seems very hard to understand those parameters in my knowledge of programming, from the documentation and some examples I came up with a question: What If I want to set all edge weights to be the same (for example: 1)?

Obviously I don't want to use

boost::add_edge(vertice1, vertice2, weight, graph);

for endless time if the graph is big enough to have many many edges.

It would be appreciate if someone can offer some examples to run.

Upvotes: 2

Views: 509

Answers (1)

sehe
sehe

Reputation: 393603

You don't show any code (except what you don't want to write...).

The exact form would depend on that. E.g. here's with a bundled weight property:

Live On Coliru

#include <boost/graph/adjacency_list.hpp>
#include <boost/range/iterator_range.hpp>

struct VertexProps { };
struct EdgeProps { double weight; };

int main() {
    boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS, VertexProps, EdgeProps> g;

    for (auto ed : boost::make_iterator_range(edges(g)))
        g[ed].weight = 1.0;
}

Of course, you could basically achieve the same with a proper default:

struct EdgeProps { double weight = 1.0; };

and you wouldn't even need a loop.


With a property map

First adapting from the above:

auto weight_map = get(&EdgeProps::weight, g);

for (auto ed : boost::make_iterator_range(edges(g)))
    weight_map[ed] = 1.0;

Interior Properties

Which would also work with something else than bundled properties:

Live On Coliru

#include <boost/graph/adjacency_list.hpp>
#include <boost/range/iterator_range.hpp>

int main() {
    boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS, boost::no_property, boost::property<boost::edge_weight_t, double> > g;

    auto weight_map = get(boost::edge_weight, g);

    for (auto ed : boost::make_iterator_range(edges(g)))
        weight_map[ed] = 1.0;
}

External Properties

Or with completely external properties

using Graph = boost::adjacency_list<>;
Graph g(10);

std::map<Graph::edge_descriptor, double> weights;
auto weight_map = boost::make_assoc_property_map(weights);

for (auto ed : boost::make_iterator_range(edges(g)))
    weight_map[ed] = 1.0;

Lastly

If the goal is just to have identical weights, just use a constant map:

auto weight_map = boost::make_constant_property<Graph::edge_descriptor>(1.0);

Upvotes: 2

Related Questions