【问题标题】:How to set the same edge weight in a graph using a loop using Boost Graph Library?如何使用 Boost Graph Library 使用循环在图中设置相同的边权重?
【发布时间】:2017-11-30 06:24:48
【问题描述】:

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

显然我不想使用

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

如果图足够大,可以有很多条边,则可以无限期使用。

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

【问题讨论】:

  • 你的代码在哪里...
  • 还有“如果图形足够大,可以有很多顶点,则无休止的时间”——你在谈论边权重,所以只关心边。
  • @sehe 好吧,“很多很多边”也存在。

标签: c++ boost graph


【解决方案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);

【讨论】:

  • 不...不是我不想写,是我不会写..
  • 我指的是您自己的陈述-您的问题字面意思是“显然我不想使用[您知道如何编写的代码]”。我的回答对你有帮助吗?
  • 在我设置边缘权重的默认属性之后的第一个如果我想添加边缘它只是add_edge(vertice1, vertice2, graph)?
猜你喜欢
  • 2014-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-15
相关资源
最近更新 更多