【问题标题】:Pointer to a Vector of Vectors in a Function Gives 'expression must have pointer type' error指向函数中向量向量的指针给出“表达式必须具有指针类型”错误
【发布时间】:2021-01-19 05:06:26
【问题描述】:

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

【问题讨论】:

  • 您已经在问题中提到了它,但我只想回应您对参考资料的确认。原始指针很值得了解,但是一旦您开始编写任何大小的东西,您就会想从智能指针和引用的角度来考虑,只有在与旧库接口或没有其他选择时才考虑使用原始指针。

标签: c++ function pointers vector stdvector


【解决方案1】:

你会想要的

graph->at(node).size();

第一次访问是-&gt;,因为你有一个vector&lt;vector&lt;int&gt;&gt;*(一个指针)。 graph-&gt;at(node) 返回一个vector&lt;int&gt;不是一个指针),所以访问它只需通过.,而不是-&gt;

【讨论】:

    【解决方案2】:

    您需要考虑指针实际指向的内容。如果我们从vector&lt;vector&lt;int&gt;&gt;* graph 声明中去掉*,那么我们就剩下:一个向量的向量。

    因此,当您取消引用指针一次(在graph-&gt;at() 中)时,您只剩下一个向量(不是指向向量的指针)。 (-&gt; 取消引用指针,at() 调用返回相关的内部向量。)

    因此,只需将该行中的第二个 -&gt; 替换为简单的 . 运算符即可:

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

    【讨论】:

      【解决方案3】:

      问题是graph-&gt;at(node) 没有返回一个指针,所以在它上面使用-&gt;size() 是无效的。将int size = graph-&gt;at(node)-&gt;size(); 更改为int size = graph-&gt;at(node).size();

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多