读题有两种方式:
我的问题是:我可以不设置一些属性
并不是说他们不能缺席。捆绑类型是实例化的单位。
创建边缘时是否都必须设置它们?
嗯,不。这是 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;
}