How to access the contents of a vector from a pointer to the vector in C++?

Pavan Dittakavi picture Pavan Dittakavi · Aug 4, 2011 · Viewed 233.1k times · Source

I have a pointer to a vector. Now, how can I read the contents of the vector through pointer?

Answer

Seb Holzapfel picture Seb Holzapfel · Aug 4, 2011

There are many solutions, here's a few I've come up with:

int main(int nArgs, char ** vArgs)
{
    vector<int> *v = new vector<int>(10);
    v->at(2); //Retrieve using pointer to member
    v->operator[](2); //Retrieve using pointer to operator member
    v->size(); //Retrieve size
    vector<int> &vr = *v; //Create a reference
    vr[2]; //Normal access through reference
    delete &vr; //Delete the reference. You could do the same with
                //a pointer (but not both!)
}