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

后端 未结 8 911
不思量自难忘°
不思量自难忘° 2020-11-30 17:26

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

8条回答
  •  没有蜡笔的小新
    2020-11-30 18:16

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

    int main(int nArgs, char ** vArgs)
    {
        vector *v = new vector(10);
        v->at(2); //Retrieve using pointer to member
        v->operator[](2); //Retrieve using pointer to operator member
        v->size(); //Retrieve size
        vector &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!)
    }
    

提交回复
热议问题