我已经试着玩了一段时间了,我想重写一些代码,以便对一个教师学生来说更容易理解。
这是最初的代码:
typedef pair<int, int> iPair;
// un graf directionat cu reprezentare prin lista de adiacenta
class Graph
{
int V; // Numar de noduri
// Lista care retine nodul si costul muchiei pentru fiecare pereche
list< pair<int, int> > *adj;
public:
Graph(int V); // constructorul
// adauga o muchie grafului
void addEdge(int u, int v, int w);
// printeaza mst-ul rezultat
void primMST(int numberElemOp);
};
// aloca memorie pentru lista de adiacenta
Graph::Graph(int V)
{
this->V = V;
adj = new list<iPair> [V];
}
void Graph::addEdge(int u, int v, int w)
{
adj[u].push_back(make_pair(v, w));
adj[v].push_back(make_pair(u, w));
} ATM机我想要一双我自己定制的:
# define INF 0x3f3f3f3f
// pereche int int denumita iPair
struct Pair {
int first;
int second;
};
struct Pair* newPair(int first, int second){
struct Pair* newPair = (struct Pair*)malloc(sizeof(struct Pair));
newPair->first = first;
newPair->second = second;
return newPair;
}
// un graf directionat cu reprezentare prin lista de adiacenta
class Graph
{
int V; // Numar de noduri
// Lista care retine nodul si costul muchiei pentru fiecare pereche
list< Pair > *adj;
public:
Graph(int V) {
this->V = V;
adj = new list<Pair> [V];
}; // constructorul
// adauga o muchie grafului
void addEdge(int u, int v, int w){
adj[u].push_back(newPair(v, w)); // http://www.cplusplus.com/reference/list/list/push_back/ pentru push back
adj[v].push_back(newPair(u, w));
};我想我尊重这些类型,但是我不太明白这个错误:
prog.cpp: In member function 'void Graph::addEdge(int, int, int)':
prog.cpp:35:33: error: no matching function for call to 'std::__cxx11::list<Pair>::push_back(Pair*)'
adj[u].push_back(newPair(v, w));在我的脑海中,我把我的定制对交给列表,它应该被推到列表中。有什么问题吗?
发布于 2018-11-04 11:33:02
您所得到的编译错误是因为:
struct Pair* newPair(int first, int second);...returns指向Pair对象(Pair*)的指针,因此当您这样做时:
adj[v].push_back(newPair(u, w)); ...you正在尝试推动一个Pair*,在那里需要一个简单的Pair。
这里的简单解决方法是不动态分配Pair对象:
// You don't need to prefix "Pair" with "struct" in C++:
Pair newPair(int first, int second) {
return { first, second };
}您的代码还有其他一些缺陷,其中一些是相当“危险”的。不应该手动分配std::list数组,这很容易出错(您需要注意复制Graph结构和释放内存),只需使用std::vector
std::vector<std::list<Pair>> adj;
// No needs to store the value of V since you can retrieve it with adj.size()
Graph(int V) : adj(V) { }此外,std::list通常是个坏主意。您应该使用std::vectors:
std::vector<std::vector<Pair>> adj;
Graph(int V) : adj(V) { }Graph的“更好”版本是:
struct Edge {
const int destination;
const int weight;
};
class Graph {
// Adjacency list:
std::vector<std::vector<Edge>> adj;
public:
Graph(int V) : adj(V) { }
void addEdge(int from, int to, int weight) {
adj[from].push_back({to, weight});
adj[to].push_back({from, weight});
}
};https://stackoverflow.com/questions/53140202
复制相似问题