简体   繁体   中英

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

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..

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 .

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 * .

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM