简体   繁体   中英

Print a Member of Struct in a Vector of Lists of Structs

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?

*gr.weight does not deference iterator first. It is equivalen to *(gr.weight) .

Change this to (*gr).weight or gr->weight;

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;
}

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.

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