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

后端 未结 8 836
不思量自难忘°
不思量自难忘° 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:13
    vector<int> v;
    v.push_back(906);
    vector<int> * p = &v;
    cout << (*p)[0] << endl;
    
    0 讨论(0)
  • 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<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!)
    }
    
    0 讨论(0)
提交回复
热议问题