指向函数中向量的向量的指针给出 'expression must have pointer type' 错误
Pointer to a Vector of Vectors in a Function Gives 'expression must have pointer type' error
Visual Studio 代码为行 int size = graph->at(node)->size();
提供了 'expression must have pointer type' 错误。我知道我可以使用 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)
returns a vector<int>
( 不是 指针),因此只需通过 .
而不是 [=11] 即可访问它=].
您需要考虑您的指针实际指向的是什么。如果我们从 vector<vector<int>>* graph
声明中去掉 *
,那么我们就剩下这个:向量的向量。
因此,当您取消引用指针 一次 (在 graph->at()
中)时,您只剩下一个向量(而不是 指针 到矢量)。 (->
取消引用指针,at()
调用 returns 相关的内部向量。)
因此,只需用一个简单的 .
运算符替换该行中的第二个 ->
:
#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)
没有 return 指针,因此在其上使用 ->size()
是无效的。将 int size = graph->at(node)->size();
更改为 int size = graph->at(node).size();
。
Visual Studio 代码为行 int size = graph->at(node)->size();
提供了 'expression must have pointer type' 错误。我知道我可以使用 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)
returns a vector<int>
( 不是 指针),因此只需通过 .
而不是 [=11] 即可访问它=].
您需要考虑您的指针实际指向的是什么。如果我们从 vector<vector<int>>* graph
声明中去掉 *
,那么我们就剩下这个:向量的向量。
因此,当您取消引用指针 一次 (在 graph->at()
中)时,您只剩下一个向量(而不是 指针 到矢量)。 (->
取消引用指针,at()
调用 returns 相关的内部向量。)
因此,只需用一个简单的 .
运算符替换该行中的第二个 ->
:
#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)
没有 return 指针,因此在其上使用 ->size()
是无效的。将 int size = graph->at(node)->size();
更改为 int size = graph->at(node).size();
。