如何在C++中将构造函数的新输入推回构造函数的默认输入?

How do i push back the new input of constructor to the default input of the constructor in C++?

本文关键字:构造函数 输入 默认 新输入 C++      更新时间:2023-10-16

我有一个类在 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(( 函数没有正确使用。有人知道怎么做吗?谢谢。

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

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
}
}
相关文章: