How can I push_back data in a vector via a vector:

2019-07-26 05:40发布

问题:

I 'd like to use a vector::pointer so as to push_back data in it..

int num;
vector<int> v;
vector<int>::pointer ptr;

ptr = &v[0];

ptr->push_back(num);  // fail
ptr.push_back(num);  // fail
ptr.push_back(&num);  // fail
*ptr.push_back(num);  // fail

nothing appears to work.. any ideas would be appreciated..

回答1:

You can't. You need to use the original vector object.

If you'd like to have a pointer to a vector, you can do the following:

vector<int> v;
vector<int> *pointer = &v;

v.push_back(4);
pointer->push_back(3);

As a comment, the type of vector<int>::pointer in your code should be int *.



回答2:

You are misunderstanding what vector::pointer is. That's a type for a pointer to an element in the vector, not a pointer to a vector itself.

That aside, it's not clear to me why you would want to do this since . notation works just fine and saves you the pointer dereference on each access. If you find yourself typing in vector<int> *vecPtr = new vector<int>;, take a deep breath and ask why you cannot use RAII.



回答3:

in this case ptr is an int* not a pointer to a vector<int> so it cannot perform vector operations. When you make the assignment:

ptr = &v[0];

you're assigning the pointer to the address containing the integer at v[0], not assigning a reference to the vector. To do what you want, you need to do the following:

int num;
vector<int> v;
vector<int>* ptr;

ptr = &v;

ptr->push_back(num);