首页 > 解决方案 > 如何将构造函数的新输入推回 C++ 中构造函数的默认输入?

问题描述

我有一个类可以在 C++ 中实现图形,如下所示。这是默认编码,不能修改。

Graph(vector<Edge> const &edges, int N)
{
    // construct a vector of vectors of Pairs to represent an adjacency list
    vector<vector<Pair> > adjList;
    // resize the vector to N elements of type vector<Pair>
    adjList.resize(N);

    // add edges to the directed graph
    for (auto &edge: edges)
    {
        int src = edge.src;
        int dest = edge.dest;
        int weight = edge.weight;

        // insert at the end
        adjList[src].push_back(make_pair(dest, weight));
    }

    this->N = N;
}

在主程序中,我有构造函数的默认输入,如下所示。我必须检查图表是否有循环。如果没有,程序必须生成随机边,直到在图中找到循环。默认图不包含循环,它的边如下:

vector<Edge> edges =
    {
        // (x, y, w) -> edge from x to y having weight w
        { 0,1,6 }, { 0,2,12 }, { 1,4,9 }, { 3,4,1 }, { 3,2,4 }
    };

我尝试使用下面的代码将随机边附加到默认图。但是,它不起作用。

do
{
  src=rand()%5;
  dest=rand()%5;
  weight=rand()%20;

  vector<Edge> edges1{
    {src, dest, weight}};

  Graph graph1(edges1,N);
  graph.push_back(graph1);

  if(graph.isCyclic())
  {
    //print the graph
  }
}while(!graph.isCyclic());

我认为 push_back() 函数没有正确使用。有谁知道怎么做?谢谢。

标签: c++

解决方案


根据提供的有限信息,以下似乎可行。

vector<Edge> edges = ...;
for (;;)
{
    int src=rand()%5;
    int dest=rand()%5;
    int weight=rand()%20;
    Edge new_edge{src, dest, weight};
    edges.push_back(new_edge);
    Graph graph(edges, N);
    if (graph.isCyclic())
    {
        //print the graph
        break; // exit the loop
    }
}

但是这段代码每次循环都会重新创建图形,因此可能会有更有效的方法。

更新

似乎以下可能有效,它避免每次都重新创建图表

vector<Edge> edges = ...;
Graph graph(edges, N);
for (;;)
{
    int src=rand()%5;
    int dest=rand()%5;
    int weight=rand()%20;
    graph.adjList[src].push_back(std::make_pair(dest, weight));
    if (graph.isCyclic())
    {
        //print the graph
        break; // exit the loop
    }
}

推荐阅读