我试图将矢量存储在增强图的顶点中。 我正在使用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
并收到以下错误消息(仅限第一个块):
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));
问题是标记为关键的行。当注释掉时,它会编译。我究竟做错了什么?
答案 0 :(得分:1)
这是常见问题。
您需要在与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