【问题标题】:Can Someone help me point out where my code is going wrong with the output?有人可以帮我指出我的代码在输出中哪里出错了吗?
【发布时间】: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

Live demo

【问题讨论】:

  • 您是否使用调试器逐步执行代码?
  • 请提供您得到错误答案的输入内容。
  • 请定义样本输入、所需输出,并将其与您得到的输出进行比较。
  • 请选择一个对有相同问题的其他人有用的标题。
  • 打印sub_vector的内容,然后再添加到main_vector。然后考虑范围和生命周期。 (您可以通过移动一行来解决此问题。)

标签: c++ algorithm output


【解决方案1】:

您的 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();
}

【讨论】:

  • 你能解释一下为什么需要 Clear() 语句吗?向量不是类似于python中的列表吗?我们不能覆盖它们吗?
  • @KanishkMewal 第一次通过循环时,它将 1 5 4 写入子向量。第二次如果它不调用 clear() 它只是将元素再次添加到子向量中,其中仍然有 1 5 4 。所以主向量在下一个索引中得到 1 5 4 1 2...。 Clear() 确保子向量将按预期获得 1 2 8 9 3。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-10-27
  • 2021-09-15
  • 1970-01-01
  • 1970-01-01
  • 2015-03-13
  • 2021-10-18
  • 2017-11-28
相关资源
最近更新 更多