【发布时间】:2021-12-08 04:12:12
【问题描述】:
#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
【问题讨论】:
-
您是否使用调试器逐步执行代码?
-
请提供您得到错误答案的输入内容。
-
请定义样本输入、所需输出,并将其与您得到的输出进行比较。
-
请选择一个对有相同问题的其他人有用的标题。
-
打印
sub_vector的内容,然后再添加到main_vector。然后考虑范围和生命周期。 (您可以通过移动一行来解决此问题。)