我需要检查一下:
1)我没有插入现有边缘 也就是说,如果我在图中有5个顶点 - 从0到4的索引然后我不能通过索引(0,6)添加反转,例如
2)检查以避免插入相同的顶点 但我无法弄清楚如何正确地做到这一点
我的代码:
bool Graph::addEdge(const Edge& edge)
{
if (edge.mStartIndex == edge.mEndIndex)
return false;
//if (mVertexList[edge.mEndIndex] != edge.mStartIndex)
{
mVertexList[edge.mStartIndex].emplace_back(edge.mEndIndex, edge.mWeight);
mVertexList[edge.mEndIndex].emplace_back(edge.mStartIndex, edge.mWeight);
}
return true;
}
边:
struct Edge
{
Edge(VertexIndex startIndex, VertexIndex endIndex, float weight);
VertexIndex mStartIndex;
VertexIndex mEndIndex;
float mWeight;
};
struct AdjacentVertex
{
AdjacentVertex(VertexIndex index, float weight);
VertexIndex mIndex;
float mWeight;
};
class Graph
{
public:
using AdjacencyList = std::vector<AdjacentVertex>;
Graph(VertexIndex numVertices);
VertexIndex numVertices() const;
const AdjacencyList& adjacencyList(VertexIndex index) const;
bool addEdge(const Edge& edge);
void removeEdge(const Edge& edge);
private:
using VertexList = std::vector<AdjacencyList>;
VertexList mVertexList;
};
答案 0 :(得分:1)
要检查边数是否过高,您可以执行以下操作:
if (edge.mStartIndex >= numVertices() || edge.mEndIndex >= numVertices())
{
// Handle situation when edge number is out of bound
}
您可以使用find_if检查邻接列表是否已包含此边缘:
auto it = std::find_if(
mVertexList[edge.mStartIndex].cbegin(),
mVertexList[edge.mStartIndex].cend(),
[&edge](const AdjacentVertex& node) {
/* Check if the current edge points to edge.mEndIndex */
return node.mEnd == edge.mEndIndex;
}
);
if (it != mVertexList[edge.mStartIndex].cend()) {
// Handle situation when you already have this edge in the list
}