简体   繁体   中英

multiple values at one vector index

I found this code online for a adjacency list that uses a vector of a pair of ints. I'm trying to understand the code and can't quite figure out what this specific line is doing in the addEdge function: adj[u].push_back(make_pair(v, wt)); . adj is the name of the vector. I get confused in the print method. When it prints, i don't understand where the source node is being stored. I get that the destination node and weight are being stored as a pair, but where does the source node int get saved? I tried experimenting with the code to understand what was going on, as seen with this line in the print function: cout << "Index: " << u << " "; but it didn't help. Here is the code:

void addEdge(vector <pair<int, int> > adj[], int u, 
                                     int v, int wt) 
{ 
    adj[u].push_back(make_pair(v, wt)); 
    adj[v].push_back(make_pair(u, wt)); 
} 
  
// Print adjacency list representaion ot graph 
void printGraph(vector<pair<int,int> > adj[], int V) 
{ 
    int v, w; 
    for (int u = 0; u < V; u++) 
    { 
        cout << "Node " << u << " makes an edge with \n"; 
        for (auto it = adj[u].begin(); it!=adj[u].end(); it++) 
        { 
            cout << "Index: " << u << " ";
            v = it->first; 
            w = it->second; 
            cout << "\tNode " << v << " with edge weight ="
                 << w << "\n"; 
        } 
        cout << "\n"; 
    } 
} 
  
// Driver code 
int main() 
{ 
    int V = 5; 
    vector<pair<int, int> > adj[V]; 
    addEdge(adj, 0, 1, 10); 
    addEdge(adj, 0, 4, 20); 
    addEdge(adj, 1, 2, 30); 
    addEdge(adj, 0, 3, 40); 
    addEdge(adj, 1, 4, 50); 
    addEdge(adj, 2, 3, 60); 
    addEdge(adj, 3, 4, 70); 
    addEdge(adj, 0, 2, 10);
    printGraph(adj, V); 
}

For reference, this is the output for the first two nodes:

Node 0 makes an edge with
Index: 0 Node 1 with edge weight =10
Index: 0 Node 4 with edge weight =20
Index: 0 Node 3 with edge weight =40
Index: 0 Node 2 with edge weight =10

Node 1 makes an edge with
Index: 1 Node 0 with edge weight =10
Index: 1 Node 2 with edge weight =30
Index: 1 Node 4 with edge weight =50

From your code adj is an array of vectors. So adj[u] is a vector and .push_back stores the node in that particular vector. push_back(), begin() and end() are methods in the vector. begin() returns an iterator to the first element (in your case it is a pair) so it is an iterator to a pair and you access the elements using it->first and it-second and you go to the next element (iterate) using it++

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