Home > Blockchain >  Vector of pointers saving a pointer to a vector of ints
Vector of pointers saving a pointer to a vector of ints

Time:07-22

just wondering if you can point to a pointer that points to a vector of ints. And save the pointer that points to a vector of ints. Here's the code I'm trying to pull off. Probably dosen't make sense but I'm trying to make it work for a while now, bare with me. But I want to pull this way somehow.

int n, q;
cin >> n >> q;
vector <int*> ar;

for (int i=0;i<n;i  ){
    
    int k;
    cin >> k;

    vector< int >  *vec;

    for(int j = 0;j<k;j  ){
        (*(vec j)).push_back(cin.get());

    }
    ar.push_back(&(vec));


}

Thanks for the possible help. Haven't seen this asked in here, just things a bit different than this.

CodePudding user response:

I think this is what you're trying to achieve here:

int n, q;
cin >> n >> q;
vector<vector<int>*> ar;
for (int i=0;i<n;i  ){
    int k;
    cin >> k;
    vector<int> *vec = new vector<int>;
    for(int j = 0;j<k;j  ){
        vec->push_back(cin.get());
    }
    ar.push_back(vec);    
}
// do not forget to delete the inner vectors before removing them from ar!

What you end up with is a vector ar that contains pointers to other vectors which in turn contain ints.

I don't see though why you would want to store pointers here at all, a nested vector works fine:

int n, q;
cin >> n >> q;
vector<vector<int>> ar;
for (int i=0;i<n;i  ){
    int k;
    cin >> k;
    vector<int> vec;
    for(int j = 0;j<k;j  ){
        vec.push_back(cin.get());
    }
    ar.push_back(vec);    
}

CodePudding user response:

in C/C you can point to litteraly anyting, heck event to nothing or to itself (void*) but if you wath to make a matrix just use int a[][] or std::vector<std::vector<int>> m

  • Related