Reputation: 19
I have a struct; it looks like this:
struct Edge { //Represents an edge
int v1, v2; // From vertex, To vertex
double weight; // Edge weight
Edge(int vertex1, int vertex2, double wt) : // Edge constructor
v1{ vertex1 }, v2{ vertex2 }, weight{ wt } {}; // from, to, weight
};
I have a vector of lists of these structs; it looks like this:
vector<list<Edge>> adjacent;
I've already got my vector of lists initialized, but I can't figure out how to print the weight member of all my edges.
list<Edge> ::iterator gr; //list iterator
for (int x = 0; x < numVertices; x++) {
for (gr = adjacent[x].begin(); gr != adjacent[x].end(); ++gr) {
cout << *gr.weight;
}
}
This does not work. VS tells me it does not have a member "weight". Anyone have a solution?
Upvotes: 1
Views: 67
Reputation: 43234
Should be:
cout << gr->weight;
Also equivalent to doing:
cout << (*gr).weight;
The reason why yours did not compile is because of operator precedence
:
The *a
(indirection) operator has a lower precedence than the .
(member-access) operator. So in your case, it was trying to find a member of the iterator called weight
, which failed.
Upvotes: 0
Reputation: 6125
gr
is an iterator, which in many respects behaves like a pointer, so you should use gr->weight
rather than *gr.weight
.
Consider range-based for
loops instead:
for (const auto &edgeList : adjacent)
{
for (const auto &edge : edgeList)
{
cout << edge.weight << ' ';
}
cout << endl;
}
Upvotes: 1
Reputation: 1881
*gr.weight
does not deference iterator
first. It is equivalen to *(gr.weight)
.
Change this to (*gr).weight
or gr->weight;
Upvotes: 2