我在 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;
现场演示
#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/