boost - 在 discover_vertex 访问者中改变图的权重

标签 boost boost-graph visitor-pattern

是否可以在算法(在本例中为 dijkstra)运行时更改图的权重?

在下面的代码中我得到一个编译器错误:

'g' : you cannot assign to a variable that is const

struct WeightVisitor : public boost::default_dijkstra_visitor
{
    template <typename Vertex, typename Graph> void
        discover_vertex(Vertex v, Graph & g)
    {
        /// Get parent
        Vertex parentVertex = boost::in_edges(v, g).first->m_source;

        typedef typename boost::graph_traits< Graph >::edge_descriptor edge_t;
        edge_t edgeDescriptor;

        std::pair<edge_t, bool> ed = boost::edge(parentVertex, v, g);
        if (tTrue == ed.second)
        {
            edgeDescriptor = ed.first;

            //put(&EdgeValueType::weight, tree, edgeDescriptor, i_wtNewWeight);
            g[edgeDescriptor].weight = rand() % 100;
            std::cout << "TimeStamp: " << g[edgeDescriptor].weight << std::endl;
        }
        else
        {
            std::cout << "Warning: No edge between input vertices" << std::endl;
        }
    }
};

在没有引用的情况下,我正在处理图表的副本,这不是我想要的。相反,我想直接更改图表上的权重。

这里是对 Dijkstra 最短路径算法的调用:

boost::dijkstra_shortest_paths(g, root,
        boost::weight_map(boost::get(&tEdge::weight, g))
        .distance_map(boost::make_iterator_property_map(distances.begin(), boost::get(boost::vertex_index, g)))
        .predecessor_map(boost::make_iterator_property_map(predecessors.begin(), boost::get(boost::vertex_index, g)))
        .visitor(sWeightVisitor)
    );

对于顶点和边,我使用捆绑属性:

struct tVertex
{
    int id;
};

struct tEdge
{
    double weight;
};

以及图的定义

typedef boost::adjacency_list<
        boost::mapS,
        boost::vecS,
        boost::bidirectionalS,
        tVertex, tEdge>
        graph_t;

最佳答案

改变权重是危险的,这取决于算法。您可能会违反算法的某些不变量,使行为不确定(例如,它可能永远不会终止)。

但是如果您知道自己在做什么,只需在访问者中保留一个指向可变图的指针:

struct WeightVisitor : public boost::default_dijkstra_visitor
{
    graph_t* _graph;

...

并用地址实例化它:

WeightVisitor sWeightVisitor { &g };

关于boost - 在 discover_vertex 访问者中改变图的权重,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54516462/

相关文章:

c++ - Boost::graph 获取到根的路径

c++ - 用基本类型标记的 Boost Graph 边缘的简单点输出

c++ - 如何拆分字符串并使用 boost::split 保留分隔符?

c++ - boost 元组性能

c++ - 纤维用例

c++ - Boost asio 收到损坏的消息

c++ - 如何在提升图中添加自定义边标签?

c++ - 带有解引用指针的多态性会产生意想不到的结果……为什么?

language-agnostic - 访客模式的实际优势是什么?有哪些替代方案?

c++ - 与 ‘operator<<’ 不匹配(操作数类型为 ‘std::ostream’ {aka ‘std::basic_ostream<char>’ } 和 ‘const std::type_index’ )