简体   繁体   English

C ++成员参考基本类型'Vertex * const'不是结构或联合

[英]C++ Member Reference base type 'Vertex *const' is not a structure or union

I am running into trouble trying to access the methods of an object stored in a vector. 尝试访问存储在向量中的对象的方法时遇到麻烦。 I know that getEdges returns an unordered map of edge but I am missing something with how to reference a Vertex object from within a vector. 我知道getEdges返回边缘的无序贴图,但是我缺少如何从向量中引用Vertex对象的东西。 Help? 救命?

In void UndirectedGraph::minSpanningTree(): 在void UndirectedGraph :: minSpanningTree()中:

std::vector<Vertex*> visited;

if(vertices.begin() != vertices.end())
{
    visited.push_back(vertices.begin()->second);
    visited[0]->distance = 0;
}
else
{
    return;
}

std::vector<Vertex*>::const_iterator vit;
vit = visited.begin();
std::unordered_map<std::string, Edge> edges;
edges = vit -> getEdges();

In const std::unordered_map & Vertex::getEdges() const: 在const std :: unordered_map和Vertex :: getEdges()const中:

return edges;

The error: 错误:

 UndirectedGraph.cpp:112:21: error: member reference base type 'Vertex
 *const' is
       not a structure or union
         edges = vit -> getEdges();
                 ~~~ ^  ~~~~~~~~ 1 error generated.

--EDIT-- - 编辑 -

Changing 更改

edges = vit -> getEdges();

to

edges = *(vit)->getEdges();

gave me the same error. 给了我同样的错误。

vit is an iterator. vit是一个迭代器。 Iteratirs work like pointers to container elements. 迭代的工作方式类似于指向容器元素的指针。 Your container element type is Vertex* . 您的容器元素类型为Vertex* Therefore vit works like Vertex** . 因此, vit工作方式类似于Vertex**

To call a member function given a Vertex** p you would have to get to a Vertex* first. 要调用给定Vertex** p的成员函数,您必须先进入Vertex* This can be done by dereferencing p like this: 可以这样取消p的引用:

(*p)

and at this point you can call your member function like 现在您可以像这样调用您的成员函数

(*p)->getEdges()

Iterators are no different. 迭代器没有什么不同。

Note 注意

*(p)->getEdges()

is totally different from the above (and wrong). 与上述完全不同(而且是错误的)。 It is the same as 与...相同

*((p)->getEdges())

and

(p)->getEdges()

is the same as 是相同的

p->getEdges()

which is known not to work. 这是行不通的。

On a related note, if you are using raw pointers you are probably doing it wrong. 与此相关的是,如果使用原始指针,则可能做错了。 You should either store Vertex objects directly in an std::vector<Vertex> or use shared_ptr or unique_ptr in lieu of raw pointers. 您应该将Vertex对象直接存储在std::vector<Vertex>或者使用shared_ptrunique_ptr代替原始指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM