简体   繁体   中英

c++ Variable Sized Arrays

i am working on an exercise in which:

As input: The first line contains two space-separated integers denoting the respective values of (the number of variable-length arrays) and (the number of queries). Each line of the subsequent lines contains a space-separated sequence in the format ka[i]0 a[i]1 … a[i]k-1 describing the -element array located at . Each of the subsequent lines contains two space-separated integers describing the respective values of (an index in array ) and (an index in the array referenced by ) for a query.

sample input: 2 2 3 1 5 4 5 1 2 8 9 3 0 1 1 3

For output: For each pair of and values (ie, for each query), print a single integer denoting the element located at index of the array referenced by . There should be a total of lines of output.

sample out put: 5 9

And my code is:

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;


int main() {
    int n=0; int q=0;
    cin>>n>>q;
    vector<vector<int>> a;
    for(int i=0; i<n;i++){
        int k;
        cin>>k;
        for(int j=0; j<k;j++){
            cin>>a[i][j];
        }
    }
for(int i=0; i<q;i++){
    int x; int y;
    cin>>x>>y;
    cout<<a[x][y]<<endl;
}
cout<<n<<q;
return 0;

}

But when i put input, I get an error

A std::vector defaults to empty. It is not valid to call operator[] with an expression like a[i] on an empty vector .

You need to add elements to a vector using functions such as push_back or resize .

Reserve space for the vector.

vector<int> integers( 100 );

See std::vector for details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM