Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
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;
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();
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:
and at this point you can call your member function like
(*p)->getEdges()
Iterators are no different.
*(p)->getEdges()
is totally different from the above (and wrong). It is the same as
*((p)->getEdges())
(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.
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.