问题描述
Visual Studio Code给我int size = graph->at(node)->size();
行的“表达式必须具有指针类型”错误。我知道我可以使用references,但我想知道如何使用指针。
#include <vector>
using namespace std;
void getPathEdges(vector<vector<int>>* graph,int sink,int count,int node,vector<int>* path) {
if (node == sink) {
path->push_back(count);
}
else {
count++;
int size = graph->at(node)->size();
for (int i=0; i<size; i++) {
getPathEdges(graph,sink,count,i,path);
}
}
}
解决方法
你会想要的
graph->at(node).size();
第一次访问是->
,因为您有一个vector<vector<int>>*
(一个指针)。 graph->at(node)
返回一个vector<int>
(不是一个指针),因此只需通过.
而不是->
即可对其进行访问。
您需要考虑指针实际指向的内容。如果我们从*
声明中删除vector<vector<int>>* graph
,那么我们将得到:向量的向量。
因此,一旦取消引用指针一次(在graph->at()
中),则只剩下一个向量(而不是向量的指针) )。 (->
取消了指针的引用,at()
调用返回了相关的内部向量。)
因此,只需使用简单的->
运算符替换该行中的第二个.
:
#include <vector>
using namespace std;
void getPathEdges(vector<vector<int>>* graph,int sink,int count,int node,vector<int>* path)
{
if (node == sink) {
path->push_back(count);
}
else {
count++;
int size = graph->at(node).size(); // Only dereference ONCE!
for (int i = 0; i < size; i++) {
getPathEdges(graph,sink,count,i,path);
}
}
}
,
问题是graph->at(node)
没有返回指针,因此对其使用->size()
是无效的。将int size = graph->at(node)->size();
更改为int size = graph->at(node).size();
。