我正在尝试将 vector 存储在 boost 图的顶点中。 我在使用 boost::read_graphviz 函数从文件读取时遇到问题。由于将顶点内容与动态属性相关联的行,编译中断。
这是一个简化版本(我们称之为 test.cpp):
#include <iostream>
#include <vector>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/graphviz.hpp>
#include <fstream>
struct Vertex
{
std::vector<int> p;
};
struct Edge
{
double w;
};
// this should be necessary, but is not 'seen' by compiler
std::ostream &
operator << ( std::ostream &OUT, const std::vector<int> &P)
{
OUT << P.size() << " ";
for( int i = 0; i < P.size(); ++i)
OUT << P[i] << " ";
return OUT;
}
// also doesn't help (and also should not be necessary as ostringstream is derived from ostream (or?)
std::ostringstream &
operator << ( std::ostringstream &OUT, const std::vector<int> &P)
{
OUT << P.size() << " ";
for( int i = 0; i < P.size(); ++i)
OUT << P[i] << " ";
return OUT;
}
int main()
{
typedef boost::adjacency_list<boost::setS, boost::setS, boost::bidirectionalS, Vertex, Edge>
Graph;
Graph
graph;
std::ifstream
in;
boost::dynamic_properties
dp;
dp.property("vector", get( &Vertex::p, graph)); // the critical line
dp.property("value", get( &Edge::w, graph));
boost::read_graphviz( in, graph, dp);
}
我编译这个使用
g++ test.cpp -lboost_graph
并得到以下错误信息(仅第一个 block ):
In file included from /usr/include/boost/graph/graphviz.hpp:25:0,
from boost_graph_test.cpp:4:
/usr/include/boost/property_map/dynamic_property_map.hpp: In instantiation of ‘std::string boost::detail::dynamic_property_map_adaptor<PropertyMap>::get_string(const boost
::any&) [with PropertyMap = boost::adj_list_vertex_property_map<boost::adjacency_list<boost::setS, boost::setS, boost::bidirectionalS, Vertex, Edge>, std::vector<int>, std
::vector<int>&, std::vector<int> Vertex::*>; std::string = std::basic_string<char>]’:
boost_graph_test.cpp:58:1: required from here
/usr/include/boost/property_map/dynamic_property_map.hpp:180:9: error: no match for ‘operator<<’ (operand types are ‘std::ostringstream {aka std::basic_ostringstream<char>}’ and ‘std::vector<int>’)
out << get_wrapper_xxx(property_map_, any_cast<typename boost::property_traits<PropertyMap>::key_type>(key));
问题是标记为关键的行。注释掉后,它会编译。我究竟做错了什么?
最佳答案
这是一个常见问题。
您需要在与 ADL 关联的命名空间中声明重载。因为 int
没有关联的命名空间,所以您必须在命名空间 std
中定义它。
将其设为静态文件以避免 ODR 冲突。
namespace std {
template <T>
static inline std::ostream& operator<<(std::ostream& os, std::vector<T> const& v) {
// ...
等等
另一种稍微更简洁的方法是定义一个 UDT(用户定义类型),它允许您在自己的命名空间中正确连接流式重载。
这是一个显示 write_graphviz
端的示例:Using two objects as hash key for an unordered_map or alternatives
关于c++ - 读取 boost 图 (boost::read_graphviz),其中顶点包含 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40685196/