#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;
}
}
原來的問題在這里:https : //www.hackerrank.com/challenges/variable-sized-arrays/problem
我知道必須有更好的方法來解決這個問題,但我想了解我的代碼的哪一部分導致了不需要的輸出,在此先感謝。
輸出應該是:
5
9
我得到的輸出:
5
1
現場演示
uj5u.com熱心網友回復:
您在 for 回圈中缺少將值插入 sub_vectors 的 vector.clear() 陳述句。
// 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();
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/335908.html
