We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
The Problem tells you everything you need to know to answer the question. You just have to read closely.
Here is my solution with added comments. I've used a raw array of arrays, dynamically allocated and via pointers, so they must be manually deleted afterwards. I could have also used a std::vector, but the question does say 'array'.
#include<iostream>usingnamespacestd;intmain(){// get length of 2D array and number of queriesintn,q;cin>>n>>q;// create 2D arrayint**a=newint*[n]();// fill 2D array with 1D subarraysfor(inti=0;i<n;i++){// get the length of the 1D array at a[i]intk;cin>>k;// create the 1D subarray with the given lengthint*i_arr=newint[k]();// fill the subarray with k valuesfor(intj=0;j<k;j++){cin>>i_arr[j];}// store the subarray in aa[i]=i_arr;}// run queries on afor(intq_num=0;q_num<q;q_num++){// get i, j as the 'query' to get a value from ainti,j;cin>>i>>j;cout<<a[i][j]<<endl;}// delete 2D array (each subarray must be deleted)for(inti=0;i<n;i++){delete[]a[i];}delete[]a;return0;}
OR with std::vector:
#include<iostream>#include<vector>usingnamespacestd;intmain(){// get length of array 'a' and number of queriesintn,q;cin>>n>>q;// create vector of vectorsvector<vector<int>>a(n);// fill each 2D vector i with k_i valuesfor(inti=0;i<n;i++){// get the length k of the vector at a[i]intk;cin>>k;// fill the vector with k valuesa[i].resize(k);for(intj=0;j<k;j++){cin>>a[i][j];}}// run queries on afor(intq_num=0;q_num<q;q_num++){// get i, j as the 'query' to get a value from ainti,j;cin>>i>>j;cout<<a[i][j]<<endl;}return0;}
Variable Sized Arrays
You are viewing a single comment's thread. Return to all comments →
The Problem tells you everything you need to know to answer the question. You just have to read closely.
Here is my solution with added comments. I've used a raw array of arrays, dynamically allocated and via pointers, so they must be manually deleted afterwards. I could have also used a std::vector, but the question does say 'array'.
OR with std::vector: