如何使用Boost Graph Library使用循环在图形中设置相同的边权重?

时间:2017-11-30 06:24:49

标签: c++ boost graph

由于Boost文档可能包含此内容,但在我的编程知识中似乎很难理解这些参数,从文档和一些示例中我提出了一个问题:如果我想将所有边权重设置为相同(例如:1)?

显然我不想使用

boost::add_edge(vertice1, vertice2, weight, graph);
如果图表足够大,可以有很多边缘,那么

无休止的时间。

如果有人可以提供一些示例来运行,我们将不胜感激。

1 个答案:

答案 0 :(得分:1)

您不显示任何代码(除了您不想写的内容......)。

具体形式取决于此。例如。这里有一个捆绑的重量属性:

<强> 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;
}

当然,基本上可以通过适当的默认值实现相同的目标:

struct EdgeProps { double weight = 1.0; };

你甚至不需要循环。

使用属性映射

首先适应上述情况:

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

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

内部属性

除了捆绑属性之外,还可以使用其他东西:

<强> 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;
}

外部属性

或具有完全外部属性

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;

最后

如果目标只是具有相同的权重,只需使用常量地图:

auto weight_map = boost::make_constant_property<Graph::edge_descriptor>(1.0);
相关问题