没有为自己的结构调用列表推回方法

List push back method not being called for own struct

本文关键字:列表 方法 调用 结构 自己的      更新时间:2023-10-16

我已经试着玩了一段时间,我想重写一些代码,让教员更容易理解。

这是初始代码:

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));

在我的脑海中,我把我的自定义配对添加到列表中,它应该被推送到列表中。怎么了?

您得到的编译错误是因为:

struct Pair* newPair(int first, int second);

返回指向Pair对象(Pair*(的指针,因此当您这样做时:

adj[v].push_back(newPair(u, w)); 

您正试图在期望简单CCD_ 4的地方推送CCD_。

这里的简单修复方法是不动态分配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});
}
};