#include <iostream>
#include <vector>
using namespace std;
/*
Sample Input:
2 2 ---------> Number of Arrays, Number of commands
3 1 5 4 -----> length of array, elements to add
5 1 2 8 9 3 -> length of array, elements to add
0 1 ---------> Command 1, row and column (first element of main vector, second element)
1 3 ---------> Command 2, row and column (second element of main vector, fourth element)
*/
int main()
{ //taking input of n and q.
int n, q;
cin >> n >> q;
//make a main array to maintain sub arrays within and use queries on it.
vector < vector<int> > main_vector;
//make a sub vector and input it's value's using for loop
vector <int> sub_vector;
//declaring a variable to take input and keep pushing into sub_vector
int input_element;
//take input length of each vector in for loop
int length_of_sub_vector;
// now take n vectors input :
for(int x = 0; x < n; x )
{
//taking input length
cin >> length_of_sub_vector;
for(;length_of_sub_vector > 0; length_of_sub_vector--)
{
cin >> input_element;
sub_vector.push_back(input_element);
}
main_vector.push_back(sub_vector);
}
//variable t and y for row and column
int t, y;
vector <int> to_print;
for(int p = 0; p < q; p ) //take input of the q following queries
{
cin >> t >> y;
to_print.push_back(main_vector[t][y]);
}
for(int u = 0; u < to_print.size(); u )
{
cout << to_print[u] << endl;
}
}
The original Problem is over here : https://www.hackerrank.com/challenges/variable-sized-arrays/problem
I know there must be a better way to solve this question but I would like to learn what part of my code is leading to the undesired output, Thanks in Advance.
Output Should be :
5
9
Output I'm getting :
5
1
CodePudding user response:
You are missing a vector.clear() statement in your for loop that inserts values into the sub_vectors.
// now take n vectors input :
for(int x = 0; x < n; x )
{
//taking input length
cin >> length_of_sub_vector;
for(;length_of_sub_vector > 0; length_of_sub_vector--)
{
cin >> input_element;
sub_vector.push_back(input_element);
}
main_vector.push_back(sub_vector);
sub_vector.clear();
}