Pair of numbers using vector
Mar 6, 2019 at 4:44am UTC
This piece of code is not using the stl pair but vector of vector.
I am not able to understand how it is taking a pair as input that too with only one "cin"
K is the number of pairs to be input
1 2 3 4 5 6 7 8 9 10
vector<vector<int >> obstacles(k);
for (int i = 0; i < k; i++) {
obstacles[i].resize(2);
for (int j = 0; j < 2; j++) {
cin >> obstacles[i][j];
}
cin.ignore(numeric_limits<streamsize>::max(), '\n' );
}
Last edited on Mar 6, 2019 at 4:45am UTC
Mar 6, 2019 at 5:10am UTC
It is in a loop, inside another loop.
A good way to get through code you don’t expect is to trace it (I prefer manually, with pen and paper, or a good text editor):
k = 3 (or whatever, but three is a good choice here)
i = 0
j = 0
cin >> obstacles[0][0]
j = 1
cin >> obstacles[0][1]
j = 2, done
cin.ignore()
i = 1
j = 0
cin >> obstacles[1][0]
j = 1
cin >> obstacles[1][1]
j = 2, done
cin.ignore()
i = 2
j = 0
cin >> obstacles[2][0]
j = 1
cin >> obstacles[2][1]
j = 2, done
cin.ignore()
i = 3 == k, done
With that, you can follow along how it reads something like
or even
12 7 // my cool list of numbers!
19 -4
52 13
Hope this helps.
Mar 6, 2019 at 5:11am UTC
> I am not able to understand how it is taking a pair as input that too with only one "cin"
You have a cin inside a for loop which iterates twice.
How is that not a 'pair' of values.
Mar 6, 2019 at 11:51am UTC
You do the 'resize' relatively late.
You could initialize the vector with value.
You do know that size is two, as in pair. So do array (and tuple).
1 2 3
vector<vector<int >> obstacles( k ); // k empty vectors (of int)
vector<vector<int >> obstacles( k, vector<int >( 2 ) ); // k two-element vectors
vector<array<int ,2>> obstacles( k ); // k two-element arrays
Can you trust that the user gives valid data?
No. Take what you can, but no half-baked entries:
1 2 3 4 5 6 7 8 9
vector<array<int ,2>> obstacles;
obstacles.reserve( k ); // still empty
int lhs = 0;
int rhs = 0;
while ( obstacles.size() < k && cin >> lhs >> rhs )
{
obstacles.push_back( {lhs, rhs} );
cin.ignore( numeric_limits<streamsize>::max(), '\n' );
}
Mar 6, 2019 at 1:33pm UTC
thanks. cool way to input pair.
Mar 6, 2019 at 3:40pm UTC
When you said a pair of numbers, I automatically thought of std::pair.
1 2 3 4 5
vector<pair<int , int >> obstacles(k);
int lhs, rhs;
while (obstacles.size() < k && cin >> lhs >> rhs)
obstacles.push_back( make_pair(lhs, rhs) );
The advantage of std::pair is that lhs and rhs do not have to be the same type.
Topic archived. No new replies allowed.