当加载 .dot 文件时,我希望在不事先定义属性的情况下读取所有属性。
在下面的代码片段中,我不想指定例如读取
weight
。其他数据集具有其他属性,我不想将它们作为变量添加到结构中。boost::dynamic_properties dp;
dp.property( "node_id", get( &Vertex::name, _graph.m_graph ) );
//dp.property("weight", get(&Edge::weight, _graph.m_graph));
boost::read_graphviz( file, _graph.m_graph, dp );
我发现另一个答案做了类似的事情,但是对于我的情况,我无法让它工作。在我的数据集中,属性位于边缘上,它们是像[weight=1]
这样的数字。我尝试编辑这一行:return boost::make_shared<dynamic_property_map_impl<unsigned int, std::string>>();
使用不同的模板类型,但我只得到了node_id:
return boost::make_shared<dynamic_property_map_impl<std::string, std::string>>();
return boost::make_shared<dynamic_property_map_impl<std::string, float>>();
完整的代码片段如下:
#include <boost/graph/graphviz.hpp>
#include <boost/program_options.hpp>
#include <boost/exception/exception.hpp>
#include <boost/exception/diagnostic_information.hpp>
#include "read_graphviz_new.cpp"
template<typename TKey, typename TValue>
class dynamic_property_map_impl : public boost::dynamic_property_map {
std::map<TKey, TValue> m_map;
public:
boost::any get(const boost::any& key) override { return m_map[boost::any_cast<TKey>(key)]; }
std::string get_string(const boost::any& key) override { std::ostringstream s; s << m_map[boost::any_cast<TKey>(key)]; return s.str(); }
void put(const boost::any& key, const boost::any& value) override { m_map[boost::any_cast<TKey>(key)] = boost::any_cast<TValue>(value); }
const std::type_info& key() const override { return typeid(TKey); }
const std::type_info& value() const override { return typeid(TValue); }
};
boost::shared_ptr<boost::dynamic_property_map>
handle_custom_properties(const std::string&,
const boost::any&,
const boost::any&) {
return boost::make_shared<dynamic_property_map_impl<unsigned int, std::string>>();
}
struct Vertex
{
std::string name;
};
struct Edge
{
float weight = 1.f;
};
typedef boost::property<boost::graph_name_t, std::string> graph_p;
typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS, Vertex, Edge, graph_p> graph_u;
void Graph::Load(std::string filepath) {
std::ifstream file(filepath);
graph_u graph;
try {
boost::dynamic_properties dp(handle_custom_properties);
dp.property("node_id", get(&Vertex::name, graph));
//dp.property("weight", get(&Edge::weight, graph));
boost::read_graphviz(file, graph, dp);
}
catch (std::exception& e) {
std::cerr << e.what() << std::endl;
}
catch (boost::exception& e) {
std::cerr << boost::diagnostic_information(e) << std::endl;
}
}
我的数据集如下所示:
strict graph {
1;
2;
3;
...
1 -- 2 [weight=1];
2 -- 3 [weight=8];
...
}