-1

I came across a situation that I couldn't explain why. I have a vector<vector<pair<int, int> > > parent that indicates parent of a specific cell. I have following code:

 // (1, 0), (1, 2), (1, 2)
 // (1, 2), (-1, -1), (1, 2)
 // (-1, -1), (2, 1), (-1, -1)
 vector<vector<pair<int, int> > > nums = {
      {make_pair(1, 0), make_pair(1, 2), make_pair(1, 2)},
      {make_pair(1, 2), make_pair(-1, -1), make_pair(1, 2)},
      {make_pair(-1, -1), make_pair(2, 1), make_pair(-1, -1)}};
  int r = 0;
  int c = 1;
  while (nums[r][c] != make_pair(r, c)) {
    cout << nums[r][c].first << " " << nums[r][c].second << endl;  // 1, 2
    r = nums[r][c].first;   // 1
    c = nums[r][c].second;  // -1
    cout << "r: " << r << " c: " << c << endl;
  }

I 'm not sure why in the first iteration of while loop for c = nums[r][c].second; it returns -1 instead of 2.

ZigZagZebra
  • 1,349
  • 3
  • 14
  • 25
  • 1
    By that point, you've already assigned a new value to `r`. On the first iteration, you will have `c = nums[1][1].second`. – François Andrieux Jun 20 '17 at 15:25
  • Also, you don't need all the `make_pair()` noise. Just use brace initialisation: `std::vector< std::pair > blah{ {21, 42}, {101, 404}, }` (Yes, it also works for nested `vector`s.) – underscore_d Jun 20 '17 at 15:29

1 Answers1

1

In first iteration,

 r=num[0][1].first = 1.

Therefore

c=num[1][1].second = - 1.  
Jarod42
  • 203,559
  • 14
  • 181
  • 302
Pushan Gupta
  • 3,697
  • 5
  • 23
  • 39