我正在尝试将自己从R转换为C ++,并且正在努力解决特定的图形问题。我有一个名为" Gra"如下。
int main(){
string Gra[4][5] = {{"V0", "V1", "V2", "V3", "V4"},
{"V5", "V6", "NA", "NA", "V7"},
{"V8", "V9", "NA", "NA", "V10"},
{"V11", "V12", "V13", "V14", "V15"}};
" V0"表示节点和" NA"不是。该矩阵来自名为" base"
的矩阵 int base[4][5] = {{1, 1, 1, 1, 1},
{1, 1, 0, 0, 1},
{1, 1, 0, 0, 1},
{1, 1, 1, 1, 1}};
typedef float Weight;
typedef boost::property<boost::edge_weight_t, Weight> WeightProperty;
typedef boost::property<boost::vertex_name_t, std::string> NameProperty;
typedef boost::adjacency_list < boost::listS, boost::vecS, boost::directedS,
NameProperty, WeightProperty > Graph;
typedef boost::graph_traits < Graph >::vertex_descriptor Vertex;
typedef boost::property_map < Graph, boost::vertex_index_t >::type IndexMap;
typedef boost::property_map < Graph, boost::vertex_name_t >::type NameMap;
typedef boost::iterator_property_map < Vertex*, IndexMap, Vertex, Vertex& > PredecessorMap;
typedef boost::iterator_property_map < Weight*, IndexMap, Weight, Weight& > DistanceMap;
Graph g;
问题出在哪里,试图在循环中描述图形。我想将节点声明为
Vertex V0 = boost::add_vertex(std::string("V0"), g); // Struggling to implement this in a loop
Vertex V1 = boost::add_vertex(std::string("V1"), g);
Vertex V2 = boost::add_vertex(std::string("V2"), g);
Vertex V3 = boost::add_vertex(std::string("V3"), g);
Vertex V4 = boost::add_vertex(std::string("V4"), g);
Vertex V5 = boost::add_vertex(std::string("V5"), g);
Vertex V6 = boost::add_vertex(std::string("V6"), g);
Vertex V7 = boost::add_vertex(std::string("V7"), g);
Vertex V8 = boost::add_vertex(std::string("V8"), g);
Vertex V9 = boost::add_vertex(std::string("V9"), g);
Vertex V10 = boost::add_vertex(std::string("V10"), g);
Vertex V11 = boost::add_vertex(std::string("V11"), g);
Vertex V12 = boost::add_vertex(std::string("V12"), g);
Vertex V13 = boost::add_vertex(std::string("V13"), g);
Vertex V14 = boost::add_vertex(std::string("V14"), g);
Vertex V15 = boost::add_vertex(std::string("V15"), g);
我试图复制这个是通过这样的循环。
for ( int i=0; i < 4; i++) // So this will run along all elements of our base vector
{
for ( int j=0; j < 5; j++) // Length is the number of elements in our array
{
if( !(Gra[i][j] == "NA")) // Whilst going along each element inspecting whether it is a true node
{
Vertex Gra[i][j] = boost::add_vertex(std::Gra[i][j], g); // This is where the problem is
}
}
}
所以问题来自于使用字符串来定义Vertex类的这个对象。身体可以帮助我吗?我很确定这是一个我正在努力解决的命名惯例问题。如果这个问题得到解决,那么我可以在创建边缘方面解决其余的问题,我也有同样的问题试图调用类的对象&#34; vertex&#34;使用字符串。
先谢谢Cyrill
答案 0 :(得分:2)
表达式!Gra[i][j] == "NA"
不会达到预期效果。它将首先检查Gra[i][j]
是否为“false”,然后将布尔结果与字符串"NA"
进行比较。
相反,要么在等式检查周围使用括号,要么进行不等的检查。所以要么
!(Gra[i][j] == "NA")
或
Gra[i][j] != "NA"
还有一个问题是在内部循环中声明了一个局部数组数组变量Gra
,这将导致与外部Gra
变量发生冲突。我想这就是你在那里使用std::Gra
的原因,但Gra
未在标准命名空间中声明。您也不能使用::Gra
,因为Gra
未在全局命名空间中声明。
不是在内部循环中声明一个新变量,而是在循环外声明一个数组Vertexes
:
Vertex Vertexes[4][5];
然后使用该变量存储boost::add_vertex
的结果。