c++ - Boost 捆绑属性 : Do I need to initialize all properties for each edge?

标签 c++ boost graph properties

我在 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;

最佳答案

读题有两种方式:

My question is: can I not set some properties

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

do they all have to be set when creating the edge?

嗯,不。这是 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;
}

关于c++ - Boost 捆绑属性 : Do I need to initialize all properties for each edge?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50366144/

相关文章:

c++ - boost shared_from_this<>()

c++ - 在C++中合并排序

c++ - Const 放置以停止使用 boost shared_ptr 编辑指针数据

graph - Graphviz 是此类图的最佳工具吗?

c++ - 使用 Boost Graph 库查找所有路径

c++ - 如何在 Linux 上查找大型项目的头文件依赖项

c++ - 为什么在boost::bind中指定了参数placer后,调用时省略了?

c++ - 套接字创建的 Shared_Ptr - 出了什么问题?

graph - 如何在JanusGraph中将权重与系数求和?

c# - 尝试在 C++ 中加载 COM 包装的 DLL 时出现未处理的异常