【发布时间】:2017-10-20 21:55:15
【问题描述】:
我目前正在尝试在现有 c++ 项目中使用 boost 图形库。我想将自定义类的对象存储在提升图中。下面是一个小示例,其中包含一个自定义类定义,其中包含两个成员(一个字符串和一个 int)及其对应的 getter 方法。
我有几个问题:
- 如何在 Graphviz 输出中包含字符串和 int 值?我使用
boost::make_label_writer发现了这个answer 与一个类似的问题,但我不确定我的示例是否可以被采用(我正在使用自定义类和共享指针)。 - 在图中不能多次存储相同的对象(相同的字符串和 int 值)。因此,我在自定义类中重载了两个比较运算符。我还读到我必须将图形类型定义的第二个模板参数更改为
boost::setS但这会导致编译器的错误消息非常长... -
假设我创建了一个自定义类的新对象:如何检查它是否已存储在图中?
#include <iostream> #include <boost/graph/graphviz.hpp> class my_custom_class { public: my_custom_class(const std::string &my_string, int my_int) : my_string(my_string), my_int(my_int) {} virtual ~my_custom_class() { } std::string get_my_string() const { return my_string; } int get_int() const { return my_int; } bool operator==(const my_custom_class &rhs) const { return my_string == rhs.my_string && my_int == rhs.my_int; } bool operator!=(const my_custom_class &rhs) const { return !(rhs == *this); } private: std::string my_string; int my_int; }; namespace boost { enum vertex_my_custom_class_t { vertex_my_custom_class = 123 }; BOOST_INSTALL_PROPERTY(vertex, my_custom_class); } int main() { typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS, boost::property<boost::vertex_my_custom_class_t, std::shared_ptr<my_custom_class>>> graph_t; typedef boost::graph_traits<graph_t>::vertex_descriptor vertex_t; std::shared_ptr<my_custom_class> object_one = std::make_shared<my_custom_class>("Lorem", 123); std::shared_ptr<my_custom_class> object_two = std::make_shared<my_custom_class>("ipsum", 456); std::shared_ptr<my_custom_class> object_three = std::make_shared<my_custom_class>("Lorem", 123); std::cout << "object one: " << object_one->get_int() << "; " << object_one->get_my_string() << std::endl; std::cout << "object two: " << object_two->get_int() << "; " << object_two->get_my_string() << std::endl; std::cout << "object three: " << object_three->get_int() << "; " << object_three->get_my_string() << std::endl; std::cout << std::endl; std::cout << "object one == object two: " << (*object_one == *object_two) << std::endl; std::cout << "object one == object three: " << (*object_one == *object_three) << std::endl; std::cout << std::endl; graph_t graph; vertex_t vertex_one = boost::add_vertex(object_one, graph); vertex_t vertex_two = boost::add_vertex(object_two, graph); vertex_t vertex_three = boost::add_vertex(object_three, graph); boost::add_edge(vertex_one, vertex_two, graph); boost::add_edge(vertex_one, vertex_three, graph); boost::write_graphviz(std::cout, graph); return 0; }
程序输出:
object one: 123; Lorem
object two: 456; ipsum
object three: 123; Lorem
object one == object two: 0
object one == object three: 1
digraph G {
0;
1;
2;
0->1 ;
0->2 ;
}
【问题讨论】:
标签: boost boost-graph