我正在尝试在可变大小的数组上解决此问题,但出现编译错误。不确定我出了什么问题。
Problem can be accessed in this PDF
我的解决方案尝试如下:
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int n,q,size,elem,index,smallindex;
//input of n and q
cin>>n>>q;
//declare the array a
int* bigarr = new int[q];
//assign the individual arrays to each element of the array a
for (int i=0; i<n; ++i){
//input of size of the individual array
cin>>size;
int* smallarr = new int[size];
for (int j=0; j<size; ++j){
smallarr[j] = cin>>elem;
}
bigarr[i] = smallarr;
}
//obtain index queries
for (int k=0; k<n; ++k){
cin>>index;
cin>>smallindex;
cout<<bigarr[index][smallindex];
}
}
关于此声明:
bigarr[i] = smallarr;
smallarr
是int*
指针,但是bigarr
也是int*
,即int
的数组,因此bigarr[i]
是单个int
。您无法将int*
指针分配给int
值。
如果要使bigarr
成为指向其他数组的指针的数组,则需要将bigarr
声明为int**
而不是int*
并使用new int*[q]
进行分配。
int** bigarr = new int*[q];
[另外,请注意您的代码正在泄漏所有分配的数组,因为任何地方都没有对delete[]
的调用。您需要添加它们:
int** bigarr = new int*[q];
...
for (int i=0; i<n; ++i){
...
int* smallarr = new int[size];
...
bigarr[i] = smallarr;
}
...
for (int i=0; i<n; ++i){
delete[] bigarr[i]; // <-- here
}
delete[] bigarr; // <-- here
尽管,您实际上应该完全使用std::vector
而不是手动使用new[]
/ delete[]
(您已经具有#include <vector>
:]]]
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ int n,q,size,elem,index,smallindex; //input of n and q cin>>n>>q; //declare the array a std::vector<std::vector<int> > bigarr(q); //assign the individual arrays to each element of the array a for (int i=0; i<n; ++i){ //input of size of the individual array cin>>size; std::vector<int> smallarr(size); for (int j=0; j<size; ++j){ cin>>elem; smallarr[j] = elem; } bigarr[i] = smallarr; /* alternatively: //input of size of the individual array cin>>size; bigarr[i].resize(size); for (int j=0; j<size; ++j){ cin>>elem; bigarr[i][j] = elem; } */ } //obtain index queries for (int k=0; k<n; ++k){ cin>>index; cin>>smallindex; cout<<bigarr[index][smallindex]; } }
附带说明:
我看到您正在使用q
分配bigarr
,但是随后您使用n
遍历了bigarr
。您不需要两个单独的变量。对两个任务都使用n
或q
,并摆脱另一个变量。
语句cin>>elem
返回一个istream&
而不是int
,因此您不能将表达式的结果用作要分配给smallarr[j]
的值。如上所示,您将必须分别分配elem
。