微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

指向函数中向量的指针给出“表达式必须具有指针类型”错误

如何解决指向函数中向量的指针给出“表达式必须具有指针类型”错误

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。