我有以下问题。
typedef std::pair<VertexT,CostT> LocalEdgeT;
typedef std::vector<LocalEdgeT> NeighborT;
typedef std::size_t VertexT;
typedef double CostT;
virtual const NeighborT& getNeighbors( VertexT v) const override
{
std::vector<LocalEdgeT> neighbors;
//here I'm adding elements, not important for the question
return neighbors;
}
我不能使该函数不带引用返回NeighborT,因为我必须使用大学提供给我的函数,由于某种原因它需要引用。
但是当我通过main中的以下调用返回它时:
std::vector<NeighborT> test = Object.getNeighbors(arg);
它给出了分段错误,可能是因为我正在返回对局部变量的引用。知道如何修复它,它仍然可以通过引用返回向量,并且可以与main方法中的函数调用一起使用吗?
此外,我必须使用c ++ 11标准进行编译。
一些其他信息:
我只是输入“对象”,因为我认为这对问题并不重要。在我的情况下,函数getNeighbors是Graph类的成员,该类具有一定数量的顶点和从顶点a到顶点b的所有边的向量。函数getNeighbors现在应该找到给定顶点v的所有邻居。从我的观点来看,不建议为类中的每个顶点都拥有自己的向量。
我确实有一张地图,在其中保存了所有Edge,并带有双倍的“ CostT”以沿该Edge行驶。
这是完整的课程。
typedef std::size_t VertexT;
typedef std::pair<VertexT,VertexT> EdgeT;
typedef double CostT;
class DistanceGraph
{
public:
typedef std::pair<VertexT,CostT> LocalEdgeT;
typedef std::vector<LocalEdgeT> NeighborT;
protected:
std::size_t vertexCount;
public:
DistanceGraph( int num_verts= 0)
: vertexCount(num_verts) {}
virtual ~DistanceGraph() {}
std::size_t numVertices() const { return vertexCount; }
virtual const NeighborT& getNeighbors( VertexT v) const = 0;
virtual CostT estimatedCost( VertexT from, VertexT to) const = 0;
virtual CostT cost( VertexT from, VertexT to) const = 0;
};
class CoordinateGraph : public DistanceGraph {
public:
std::map< EdgeT, CostT > allEdges;
std::vector < std::pair < double, double > > geometricPosition;
void setNumVertices( size_t);
friend std::istream& operator >> (std::istream& in,CoordinateGraph& g);
virtual const NeighborT& getNeighbors( VertexT v) const override
{
std::vector<LocalEdgeT> neighbors;
for(size_t i = 0; i < (*this).numVertices(); i++)
{
EdgeT edge = std::make_pair(v,i);
if((*this).allEdges.find(edge) != (*this).allEdges.end())
{
neighbors.push_back( std::make_pair(i,(*this).allEdges.find(edge) -> second));
}
}
return neighbors;
}
virtual CostT cost( VertexT from, VertexT to) const override
{
EdgeT edge = std::make_pair(from,to);
if((*this).allEdges.find(edge) != (*this).allEdges.end()) return (*this).allEdges.find(edge) -> second;
else return 10000000;
}
};
为了再次澄清这一点,我无法使函数getNeighbors返回NeighborT。
我看到的一种解决方案是使每个顶点的邻居成为存储在向量中的类成员。
当我调用上述函数时,上面的代码显然存在返回局部变量的问题。
最佳答案
由于您似乎很难通过引用返回邻居的向量,因此您基本上别无选择,必须将其存储在您的类中。
只需使一个std::map<VertexT, NeighborT>
类成员来存储它们。
调用getNeighbors
时,请检查现有条目并返回现有条目或创建一个新条目,然后将其添加到地图中。