如何在C++中将构造函数的新输入推回构造函数的默认输入?
How do i push back the new input of constructor to the default input of the constructor in 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(( 函数没有正确使用。有人知道怎么做吗?谢谢。
根据所提供的有限信息,似乎以下内容是可行的。
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
}
}
相关文章:
- 在构造函数中输入对象时C++类成员作用域
- 为什么复制构造函数不需要检查输入对象是否指向自身?
- 如何在C++中将构造函数的新输入推回构造函数的默认输入?
- C++ 如何根据作为输入传递的参数调用一个构造函数或另一个构造函数?
- 如何使输入文本文件成为构造函数参数?c++
- C ++回测问题:如何检查构造函数在假定失败时是否失败(给定输入的无效参数)
- std::具有两个输入参数的矢量构造函数
- 如何实现构造函数,使其仅接受使用 typeid 的输入迭代器?
- C++参数化构造函数使代码在传递大输入时停止工作
- 两个构造函数(带和不带参数),没有输入 -> 没有参数运行。跳过上述类中的构造函数
- 如何正确访问通过引用从标准输入传递给构造函数的参数的值
- 默认构造函数 Eclipse 项目中的用户输入
- 如何为作为雇员类的指针传入的构造函数输入数据
- 如何解析文本文件并使用构造函数中的文件输入来创建对象的容器
- 如何使用我的输入制作构造函数?
- 尝试声明构造函数时,输入末尾的预期"{"
- 如何将用户输入存储在变量中,该变量与默认构造函数中的变量初始化中的值不同
- 根据输入参数值调用不同的基类构造函数
- 如何编写两个初始化操作(一个作为默认初始化,另一个作为用户输入)?两者都是类的构造函数C++
- 构造函数错误:输入末尾的预期“{”