对程序故障进行分段



我正在尝试解决黑客等级中一个名为可变大小数组的问题。

input
2 2
3 1 5 4
5 1 2 8 9 3
0 1
1 3
output
5
9

问题的工作方式是你首先得到两个输入,让我们基于上面的例子,这里的"2 2"意味着我们需要 2 行数据和 2 个查询。 下一个输入是这一行中有多少数据 "3"表示 3 个输入,然后下一个输入将是该行中的数据,所以现在我们应该有

[ [1, 5, 4], [1, 2, 8, 9, 3] ]

现在请记住,在输入的第一行中,第二个输入是查询数。 所以接下来的输入将意味着我们要打印出来的数据的索引, 因此,"0 1"将是第一行中的第二个值。哪个是5,"1 3"是"9">

现在明白了这是我的代码。

#include <iostream>
#include <vector>
using std::string;
using std::cout;
using std::cin;
int main()
{
// get from the user the number of rows and queues he'll be making 
int row, noQ;
cin >> row >> noQ;
int col;
std::vector<std::vector<int>> nums;
nums.reserve(row);
for (int i = 0; i < row; i++)
{
cin >> col;
nums[i].reserve(col);
for (int j = 0; j < col; j++)
{
int data;
cin >> data;
nums[i].push_back(data);
}
}
// stores the value in the given index
std::vector<int> query;
for (int i = 0; i < noQ; i++)
{
int y, x;
cin >> y >> x;
query.push_back(nums[y][x]);
}
// print out the data from given index
for (auto x : query)
cout << x << "n";
}

我对向量很陌生,所以我不确定出了什么问题,在我输入代码中的所有数据后,我似乎遇到了 seg 错误。

std::vector<std::vector<int>> nums;

你已经使用了 vector 的默认构造函数。此向量为空,不包含任何元素。

nums[i].reserve(col);

在这里,您可以访问空向量的第i个元素。由于向量为空,因此此索引超出向量的边界。程序的行为是未定义的。

解决方案:不要访问数组中不存在的元素。在这种情况下,例如,您可以使用创建许多元素的矢量构造函数。

只是编写代码的一种更简单的方法,始终包含bits/std,因为它包含所有 stl 元素.. 并使用命名空间 std,这样您就不必总是做std::

#include <bits/stdc++.h>
using namespace std;
int main()
{
// get from the user the number of rows and queues he'll be making 
int row, noQ;
cin >> row >> noQ;
int col;
vector<vector<int>> nums;
nums.reserve(row);
for (int i = 0; i < row; i++)
{
cin >> col;
nums[i].reserve(col);
for (int j = 0; j < col; j++)
{
int data;
cin >> data;
nums[i].push_back(data);
}
}
// stores the value in the given index
vector<int> query;
for (int i = 0; i < noQ; i++)
{
int y, x;
cin >> y >> x;
cout<<nums[y][x]<<"n";
}
}

最新更新