【发布时间】:2020-05-20 19:25:27
【问题描述】:
使用 boost 图库 的read_graphviz() 读取图时,用于存储节点的内部索引与用于显示相同图的索引相比发生了变化。这在处理大图时是有问题的,因为很难将它们作为文本文件进行比较。
我写了一个小例子(见下面的源代码),我开始阅读一个小图
输入
digraph G {
0[index=0];
1[index=1];
2[index=2];
10[index=10];
}
但是,当使用 write_graphviz() 打印它时,输出顺序会发生变化:
输出
digraph G {
0[index=0];
1[index=1];
2[index=10]; /* <= mismatch here ! */
3[index=2]; /* <= and here ! */
}
虽然我理解为什么节点 index 10 会被重新影响为较小的值,例如所有索引都按升序排列,但我不明白为什么它会受到影响 index 2 而不是 3 因为它出现在索引 2 之后(在输入中)。
我猜这是因为使用的顺序必须是索引属性上的字典顺序,解释为字符串,但真的是这样吗?在我自己的程序中,节点索引超过 150,我得到以下重新排序:
0[index=0000];
1[index=0001];
2[index=0010];
3[index=0100];
4[index=0101];
5[index=0102];
6[index=0103];
7[index=0104];
8[index=0105];
9[index=0106];
10[index=0107];
11[index=0108];
12[index=0109];
13[index=0011];
14[index=0110];
15[index=0111];
我的问题:如何避免这种行为以使内部节点索引始终与我的自己的索引匹配?
这是这个简单示例的代码:
#include <iostream>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/graphviz.hpp>
using namespace std;
struct Node { std::size_t index; };
/*! \brief DAG: Directed Acyclic Graph */
typedef boost::adjacency_list<boost::listS, boost::vecS, boost::directedS, Node> DAG;
template<class IndexMap> class node_writer {
public:
node_writer(IndexMap n) : inm(n) {}
template<class Vertex> void operator()(std::ostream & out, const Vertex & v) {
out << "[index=" << inm[v] << "]";
}
private:
IndexMap inm;
};
template<class IndexMap>
inline node_writer<IndexMap> make_node_writer(IndexMap inm) {
return node_writer<IndexMap>(inm);
}
std::ostream & operator<<(std::ostream & o, const DAG & g) {
boost::write_graphviz(o, g, make_node_writer(boost::get(&Node::index, g)));
return o;
}
std::istream & operator>>(std::istream & i, DAG & g)
{
boost::dynamic_properties dp(boost::ignore_other_properties);
dp.property("index", get(&Node::index, g));
read_graphviz(i, g, dp);
return i;
}
int main(int argc, char * argv[])
{
DAG * pTree = new DAG(0);
std::stringstream dag_file;
dag_file << "digraph G {\n";
dag_file << "0[index=0];\n";
dag_file << "1[index=1];\n";
dag_file << "2[index=2];\n";
dag_file << "10[index=10];\n";
dag_file << "}";
std::cout << dag_file.str() << "\n";
dag_file >> *pTree;
std::cout << *pTree;
return 0;
}
【问题讨论】:
标签: c++ boost boost-graph