【发布时间】:2020-06-15 12:26:26
【问题描述】:
我正在学习 C++,在练习 Hackerrank 时,我第一次遇到了包含向量的向量。 This 是要解决的问题。 从下面提供的程序中,我想知道:
- 是否像我一样声明所需向量的正确方法?
- 第 27 行的语句“a.resize(i)”是否按我的预期工作?
#include<iostream>
#include<vector>
#include<array>
bool inrange(int min, int max, int x)
{
//check if x is in range
return (x >= min && x <= max);
}
int main(void)
{
int q{}, n{}; //for no. of queries & no. of elements in array
std::cin >> q >> n;
if (inrange(1, 100000, q)) //ensure q to be in specified range
{
if (inrange(1, 100000, n))
{
//for declaring vector of vectors
using innertype = std::vector<int>;
std::vector <innertype> a;
//array to store no. of elements in each ith array
std::vector <int> ki;
for (int i{ 0 }; i < n; ++i)
{
//extend vector by one element
>line 27 a.resize(i);
//get the array for ith position
int j{ 0 }; char buffer;
do
{
//extend vector at ith index by one element
a[i].resize(j);
std::cin >> a[i][j];
std::cin >> buffer;
++j;
} while (buffer != '\n');
ki.resize(j);
ki[i] = j;
}
//take indexes for query1 and query2 to print requested elements
int i{}, j{};
std::cin >> i >> j;
std::array q1request{ i,j };
std::cin >> i >> j;
std::array q2request{ i,j };
//print elements "a[i][j]"
std::cout << a[q1request[i]][q1request[j]] << '\n';
std::cout << a[q1request[i]][q2request[j]];
}
}
return 0;
}
程序在接受两个输入后终止。
调试断言失败! 表达式:向量下标超出范围
【问题讨论】:
标签: c++ vector visual-c++ dynamic-memory-allocation