c++ - 如何将构造函数的新输入推回 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
}
}
推荐阅读
- java - 多个数据源的 Spring Boot 错误(对 DialectResolutionInfo 的访问不能为空)
- database - 如何制作点“。” 下划线 '_' 的行为类似于 MongoDB 中 $text 索引中的空格
- python - Index of an element in a nested list
- visual-c++ - 对于给定的整数 n,找到 n 后面是 10 的倍数的数
- c - 我们如何使用 C 中的指针算术仅打印出两个相同符号之间的字符串的一部分
- json - 无法在 Gitlab Yaml 管道中编码 JSON
- redis - 如何检查每秒访问 Redis 的平均请求数
- json - 从 React 中的 JSON 本地文件中获取数据
- javascript - 不返回承诺时的nodemailer延迟
- python - 带有回调的 kivy Urlrequest 在移动设备上抛出错误,但在笔记本电脑上却没有,为什么?