【问题标题】:Boost Bundled Properties: Do I need to initialize all properties for each edge?Boost Bundled Properties:我需要为每条边初始化所有属性吗?
【发布时间】:2023-03-07 05:55:01
【问题描述】:

我在 boost 中创建了一个图表,并且正在使用捆绑的属性。我不需要每个边缘的每个属性,但我需要所有边缘的所有属性。我的问题是:我可以不设置一些属性还是必须在创建边缘时设置它们?

struct EdgeProperty 
{
    double weight;
    int index;
    int property_thats_only_used_sometimes;
    bool property_thats_only_used_sometimes2;
};
//would this be enough:
edge_descriptor edge = add_edge(u, v, graph).first;
graph[edge].weight = 5;
graph[edge].index = 1;

【问题讨论】:

  • 初始化所有属性有什么问题?如果您在初始化时不知道哪个边缘需要设置所有属性,那么是的,您应该将它们全部初始化。否则,只需初始化所需的属性。

标签: c++ boost graph properties


【解决方案1】:

读题有两种方式:

我的问题是:我可以不设置一些属性

并不是说他们不能缺席。捆绑类型是实例化的单位。

创建边缘时是否都必须设置它们?

嗯,不。这是 C++。在您的示例中,不将它们全部“设置”将使它们处于不确定的值。对于非原始类型,将应用默认初始化(例如 std::string 将始终获得默认值 "")。

为了防止不确定的数据,您可以简单地提供初始化,或者通过添加默认构造函数:

struct EdgeProperty {
    double weight;
    int index;
    int property_thats_only_used_sometimes;
    bool property_thats_only_used_sometimes2;

    EdgeProperty() 
      : weight(1.0), index(-1),
        property_thats_only_used_sometimes(0),
        property_thats_only_used_sometimes2(false)
    { }
};

或等效地使用 NSMI:

struct EdgeProperty {
    double weight = 1.0;
    int index     = -1;
    int property_thats_only_used_sometimes   = 0; 
    bool property_thats_only_used_sometimes2 = false;
};

进阶思路

您可能不知道,但您也可以将属性直接传递给add_edge。如果您愿意,您可以提供一个合适的构造函数来仅采用常用设置的属性:

struct EdgeProperty {
    double weight;
    int index;

    EdgeProperty(double w = 1.0, int i = -1) : weight(w), index(i)
    { }

    int property_thats_only_used_sometimes = 0;
    bool property_thats_only_used_sometimes2 = 0;
};

现在您可以简单地创建边缘:

auto edge = add_edge(u, v, EdgeProperty(5, 1), graph).first;

现场演示

Live On Coliru

#include <boost/graph/adjacency_list.hpp>

struct EdgeProperty {
    double weight;
    int index;

    EdgeProperty(double w = 1.0, int i = -1) : weight(w), index(i)
    { }

    int property_thats_only_used_sometimes = 0;
    bool property_thats_only_used_sometimes2 = 0;
};

using Graph = boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS, boost::no_property, EdgeProperty>;

int main() {
    Graph graph;
    auto u = add_vertex(graph);
    auto v = add_vertex(graph);

    //would this be enough:
    auto edge = add_edge(u, v, EdgeProperty(5, 1), graph).first;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-28
    • 1970-01-01
    • 1970-01-01
    • 2021-02-25
    • 2011-05-30
    • 1970-01-01
    • 1970-01-01
    • 2018-12-28
    相关资源
    最近更新 更多