0

I have below code and i would like to make loop for appending to the graph!

Example:

    graph[1].push_back(make_pair(2, 3)); 
    graph[2].push_back(make_pair(4, 8)); 
    graph[3].push_back(make_pair(3, 7)); 
    ...
    graph[6].push_back(make_pair(5, 8)); 

To:

// is there any better way!!!
int n,a,b;

    vector< pair<int,int> > graph[n+1]; 


for (int i = 0; i < n; i++){
        cin >> a >> b;

    graph[n].push_back(make_pair(a, b)); 
}

My main Function...

int main() 
{ 
    // n is number nodes
    int n = 6; 

    vector< pair<int,int> > graph[n+1]; 

    // create undirected graph 
    // first edge 
    graph[1].push_back(make_pair(2, 3)); 
    graph[2].push_back(make_pair(1, 3)); 

    // second edge 
    graph[2].push_back(make_pair(3, 4)); 
    graph[3].push_back(make_pair(2, 4)); 

    // third edge 
    graph[2].push_back(make_pair(6, 2)); 
    graph[6].push_back(make_pair(2, 2)); 

    // fourth edge 
    graph[4].push_back(make_pair(6, 6)); 
    graph[6].push_back(make_pair(4, 6)); 

    // fifth edge 
    graph[5].push_back(make_pair(6, 5)); 
    graph[6].push_back(make_pair(5, 5)); 

    cout << myFunction(graph, n); 

    return 0; 
} 

Would anyone help me to fix the issues! Is there any better way to solve the loop?

Yunnosch
  • 26,130
  • 9
  • 42
  • 54
Joe
  • 25
  • 5
  • What's the point of having one `vector` for each `pair` ? – Sid S Oct 29 '19 at 04:23
  • Once i get the all input from command line i would like to do loop! My loop does not seems to be work with this one: ``` graph[n].push_back(make_pair(a, b)); ``` – Joe Oct 29 '19 at 04:29
  • `vector< pair > graph[n+1];` [is not a good thing to do in C++](https://stackoverflow.com/q/57367473/10957435). –  Oct 29 '19 at 04:30
  • Ok! But is it the right way to pushback into loop? graph[n].push_back(make_pair(a, b)); – Joe Oct 29 '19 at 04:32
  • Are you trying to set the size of the vector here ` vector< pair > graph[n+1]; ` and then want to push all pairs to it? – Simson Oct 29 '19 at 04:33
  • @Joe See my answer. –  Oct 29 '19 at 04:41

1 Answers1

0

In addition to this explanation of why declaring graph this way is wrong, array access is 0-based, meaning the first item in your array is actually graph[0], and there is no graph[6]. So just subtract 1 from all of your indices (and fix the other really bad bug).


Is there any better way to solve the loop!

It is unclear to me what the formula for creating a pair here would entail, but I can tell you that you can put most things into a loop like this:

for(i =0;i<6-1 /* or whatever size you want */;i++) {
    graph[i].push_back(make_pair(/*Not sure what goes in here */)); 
    graph[i+1].push_back(make_pair(/* but it should be a start */));
        // also, this is why we do size - 1, since we are adding 1 to i here
}