简体   繁体   中英

how can i access a vector of pointers pointing to other vectors? I tried the hackerrank program variable sized arrays in c++:

Consider an n-element array a, , where each index i in the array contains a reference to an array of k(i) integers (where the value of k(i) varies from array to array).

Given a , you must answer q queries. Each query is in the format ij, where denotes an index in array a and j denotes an index in the array located at a[i]. For each query, find and print the value of element j in the array at location a[i] on a new line.

int n,q,k,input,r,s;
cin>>n>>q;
vector<int*> a;
vector<int> vec;
for(int i=0;i<n;i++)
{
   
    cin>>k;
    for(int j=0;j<k;j++)
    {
        cin>>input;
        vec.push_back(input);
    }
    a.push_back(vec.data());
}
for(int m=0;m<q;m++)
{
    cin>>r>>s;
    cout<<endl<<*(a[r]+s);
    
}  

The chief problem here is that each member of a should point to a different array. That's at least what the exercise suggests. You make all elements of a point to the same vec vector.

There's also the slight matter that vec.data() keeps changing as it grows, but that's probably solved when you fix that first problem.

Note that in C++, we'd typically use a std::vector<std::vector<int>> for this problem. The literal interpretation "each index i in the array contains a reference " wouldn't work because a C++ reference can't be a member of a vector, but the exercise does not appear to written with C++ in mind. Hence, "reference" does not mean C++ reference.

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