有必要检查向图形添加边缘的功能

时间:2018-04-03 06:44:59

标签: c++ graph

我需要检查一下:

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;
};

1 个答案:

答案 0 :(得分:1)

  1. 要检查边数是否过高,您可以执行以下操作:

    if (edge.mStartIndex >= numVertices() || edge.mEndIndex >= numVertices()) 
    {
        // Handle situation when edge number is out of bound
    } 
    
  2. 您可以使用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
    }