开发者

Printing values through pointers

I have a class Vertex and a class Graph to draw a graph. I wish to store few vertices i.e. objects of Vertex Class in the Vector of type Vertex, but due to few errors I wasn't able to store the vertex objects directly, so I am storing the references of the objects in vectors. But while displaying I wish to display the vector name on console which I am not able to do so. May be my syntaxes are incorrect. Please help me out. Below is my code for both the classes and main().

My requirement is to display "v1开发者_运维问答", "v2",... so on, on the console. But right now its only displaying the addresses on the vertices.


From what I can see, in the first for loop, you're not getting the actual value from "g1.Vertice1[i]" but trying to print the pointer. The type of Vertice1 is vector<Vertex<VertexType, EdgeType>*> (a vector of pointers to Vertex objects,) so you need to change the line so that it uses the -> operator to dereference the pointer and call of the "Vert" and print the return of that instead of trying to print the pointer's value.

Change

std::cout << g1.Vertice1[i]<<endl;

to

std::cout << g1.Vertice1[i]->Vert() <<endl;


Look at what you're adding to the g1.Vertice1 vector:

g1.Vertice1.push_back(&v1);
g1.Vertice1.push_back(&v2);

The elements of the vector are pointers, not Vertex objects. Which makes sense given that Vertice1 is declared as a vector of pointers to a specific type of Vertex.

When you iterate over the g1.Vertice1 vector and output its elements you are therefore outputting pointers which is why you are seeing addresses. So consider dereferencing those pointers in the loop that is trying to print out the vertex names.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜