简体   繁体   中英

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. Help?

In 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:

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. Iteratirs work like pointers to container elements. Your container element type is Vertex* . Therefore vit works like Vertex** .

To call a member function given a Vertex** p you would have to get to a Vertex* first. This can be done by dereferencing p like this:

(*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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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