-2

I know the reason why this is happening but don't know how to solve this as I am new to STL.

I am taking the inputs from the user and representing the weighted graph using vectors. I declared a vector pair<int,int> to store the value of the edge and the weight.

#include<iostream>
#include<vector>
using namespace std;
int main()
{
    int n,m,c;
    cout<<"Enter n,m : "<<endl;
    cin>>n>>m;
    vector<pair<int,int>> adj[n+1];
    cout<<"If un-directed input 1 else input 0: "<<endl;
    cin>>c;
    cout<<"Enter the values of u,v and the waight : "<<endl;
    for(int i=0;i<m;i++)
    {
        int u,v,w;
        cin>>u>>v>>w;
        adj[u].push_back({v,w});
        if(c==1)
            adj[v].push_back({u,w});
    }
    for(int i=0;i<=n;i++)
    {
        for(int j:adj[i])
        {
            cout<<i<<"->" << j <<endl;
        }
        cout<<endl;
    }
    cout<<"Inserted Successfully";
    return 0;
}

But when i am printing the values i am not able to compile the program. It is due to this for loop.

for(int j:adj[i])
        {
            cout<<i<<"->" << j <<endl;
        }

As the value in adj[i] is a pair of edge and weight thus ,the for_each loop is unable to convert the pair value to a single int value. This might be the reason but i am unable to solve this as i am new to the STL.

Please Help.

  • It's because `adj` is not an array/vector of integers. It's an array of `std::pair` so there is an unresolvable type mismatch – Den-Jason Nov 06 '21 at 11:30
  • Why are you creating a raw array of vectors? I don't get that. – πάντα ῥεῖ Nov 06 '21 at 11:31
  • i am creating an array of vectors because i want to keep the track of the first end of the edge in adj[i] and the second end of the edge with weight will be stored in vector using push_back(). – Vatsalya Baluni Nov 06 '21 at 11:35
  • 1
    `vector> adj[n+1];` is not valid C++. See [Why aren't variable-length arrays part of the C++ standard?](https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard) Don't use so-called "competition" or "online judge" sites as learning or teaching resources. Using them as such could be actively harmful. – Some programmer dude Nov 06 '21 at 11:36
  • *"i am not able to compile the program."* -- please provide the error message (in the question). – JaMiT Nov 06 '21 at 15:46
  • *"It is due to this for loop.*" -- this is good progress. The next step is to eliminate most of the rest of the code, to isolate the bug. Hardcode some (simple) values for `i` and `adj[i]` (don't rely on user input), then have this loop, and remove just about everything else from your code. Keep only what you need so that the first compilation error is the one you are asking about. (This is known as a "[mre]".) – JaMiT Nov 06 '21 at 15:49

1 Answers1

0

j is a pair of int in order to access the first/second int you have to use j.first/ j.second

    for(pair<int,int> j:adj[i])
    {
        cout<<i<<"->" << j.second <<endl;
    }