【发布时间】:2016-07-28 23:52:23
【问题描述】:
我正在寻找使用 c++ 从图形中随机选择一个数字的解决方案。
例如,我有一个在两个顶点之间添加边(一个或多个)的图,我如何随机选择一个数字?
一些代码:
#include <iostream>
#include <list>
#include <queue>
using namespace std;
// Graph class represents a undirected graph using adjacency list representation
class Graph
{
private:
int V; // # of vertices
list<int> *adj; // Pointer to an array containing adjacency lists
public:
Graph(int V) // Constructor
{
this->V = V;
adj = new list<int>[V];
}
void addEdge(int v, int w); // function to add an edge to graph
void print(int v, int w); //function to display
};
void Graph::addEdge(int v, int w)
{
adj[v].push_front(w); // Add w to v’s list.
adj[w].push_front(v); // Add v to w’s list.
print(v, w);
}
void Graph::print(int v, int w) {
cout << v << " - " << w << endl;}
主要是:
Graph g(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 3);
示例输出:
0 - 1
0 - 2
1 - 3
【问题讨论】:
-
离题了,但你为什么要为
adj使用裸c 样式数组?为什么不是std::vector或std::array?这样您就不需要使用V手动跟踪大小或手动删除它。 -
@MarkH 我正在使用“向量”添加顶点,所以如果有一些提示如何?
-
您可以使用
vector< list<int> >,而不是list<int> *adj。然后,在构造函数中,您将使用adj = vector< list<int> >(V)来设置向量的大小。最好使用初始化列表:Graph(int V) : adj(V) {}。参考:en.cppreference.com/w/cpp/language/initializer_list -
@MarkH 如何改变 adj[v].push_front(w); ?
-
那行保持不变。